【问题标题】:Flutter problem with parsing Complex json data解析复杂 json 数据时出现 Flutter 问题
【发布时间】:2020-08-18 17:37:05
【问题描述】:

我想用一些 json 数据进行 get 查询,我使用这个网站 https://app.quicktype.io/ 编写了这个类,它给了我这段代码

import 'dart:convert';

class Jsonclass {
  final Imei imei;

  Jsonclass({
    this.imei,
  });

  factory Jsonclass.fromJson(Map<String, dynamic> json) => Jsonclass(
        imei: Imei.fromJson(json["imei"]),
      );

  Map<String, dynamic> toJson() => {
        "imei": imei.toJson(),
      };
}

class Imei {
  final String name;
  Test test;

  Imei({
    this.name,
    this.test,
  });

  factory Imei.fromJson(Map<String, dynamic> json) => Imei(
        name: json["name"],
        test: Test.fromJson(json["test"]),
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "test": test.toJson(),
      };
}

class Test {
  String batterieState;
  String wifiState;
  String pixelState;
  String bluetoothState;
  String gpsState;
  String tactileState;
  String bafleState;
  String microState;
  String vibreurState;
  String camerafrontState;
  String camerabackState;
  String boutonState;
  String usbState;
  String kitState;
  String geroscopeState;
  String empreinteState;
  String captState;
  String greyState;
  String proximiteState;
  String lumiereState;

  Test({
    this.batterieState,
    this.wifiState,
    this.pixelState,
    this.bluetoothState,
    this.gpsState,
    this.tactileState,
    this.bafleState,
    this.microState,
    this.vibreurState,
    this.camerafrontState,
    this.camerabackState,
    this.boutonState,
    this.usbState,
    this.kitState,
    this.geroscopeState,
    this.empreinteState,
    this.captState,
    this.greyState,
    this.proximiteState,
    this.lumiereState,
  });

  factory Test.fromJson(Map<String, dynamic> json) => Test(
        batterieState: json["batterieState"],
        wifiState: json["wifiState"],
        pixelState: json["pixelState"],
        bluetoothState: json["bluetoothState"],
        gpsState: json["gpsState"],
        tactileState: json["tactileState"],
        bafleState: json["bafleState"],
        microState: json["microState"],
        vibreurState: json["vibreurState"],
        camerafrontState: json["camerafrontState"],
        camerabackState: json["camerabackState"],
        boutonState: json["boutonState"],
        usbState: json["usbState"],
        kitState: json["kitState"],
        geroscopeState: json["geroscopeState"],
        empreinteState: json["empreinteState"],
        captState: json["captState"],
        greyState: json["greyState"],
        proximiteState: json["proximiteState"],
        lumiereState: json["lumiereState"],
      );

  Map<String, dynamic> toJson() => {
        "batterieState": batterieState,
        "wifiState": wifiState,
        "pixelState": pixelState,
        "bluetoothState": bluetoothState,
        "gpsState": gpsState,
        "tactileState": tactileState,
        "bafleState": bafleState,
        "microState": microState,
        "vibreurState": vibreurState,
        "camerafrontState": camerafrontState,
        "camerabackState": camerabackState,
        "boutonState": boutonState,
        "usbState": usbState,
        "kitState": kitState,
        "geroscopeState": geroscopeState,
        "empreinteState": empreinteState,
        "captState": captState,
        "greyState": greyState,
        "proximiteState": proximiteState,
        "lumiereState": lumiereState,
      };
}

然后我写了get方法来显示数据;它工作正常,服务器发送数据,但问题是显示数据时颤动它给了我这个异常

在构建 FutureBuilder>(dirty, state: _FutureBuilderState>#ba8ab):
'_TypeError' 类型不是 'String' 类型的子类型

这是我的代码

import 'dart:convert';

void main() => runApp((JsonDataParse()));
class JsonDataParse extends StatefulWidget {
  @override
  _JsonDataParseState createState() => _JsonDataParseState();
}

class _JsonDataParseState extends State<JsonDataParse> {


  Future <List<Jsonclass>> getData() async{
    final response = await http.get('http://192.168.43.24:27017/api/posts');
    if(response.statusCode==200){
      List phones =json.decode(response.body);
      return phones.map((phone)=>new Jsonclass.fromJson(phone)).toList();
    }
    else {
      throw Exception('Failed to load Users');
    }
  }
  void initState(){
    super.initState();  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
      appBar: AppBar(
        title: Text('Mes Smartphones'),
      ),
      body: Center(
        child: FutureBuilder<List<Jsonclass>>(
          future: getData(),
          builder: (context,snapshot){
            if(snapshot.hasData){
              List<Jsonclass> phones =snapshot.data;
              return new ListView(
                children:phones.map((phone) =>Column(
                  children: <Widget>[
                     ListTile(
                        subtitle: Text('bonjour${phone.imei.name}'),
                      ),


                  ],
                )).toList(),
              );
            }
            else if(snapshot.hasError){
              return Text(snapshot.error);
            }
            return new CircularProgressIndicator();
          },
        ),
      ),
    )
    );
  }
}

【问题讨论】:

    标签: android ios json flutter dart


    【解决方案1】:

    您可能想尝试使用 toString() 方法,这对我将字符串解析为文本小部件有很大帮助。希望这会有所帮助

     ListTile(
       subtitle: Text('bonjour${phone.imei.name.toString()}'),
     ),
    return Text(snapshot.error.toString());
    

    【讨论】:

    • 谢谢它可以解决这个问题,但我有一个新问题,即没有数据发送到快照,我的意思是有来自服务器的数据,但 snapshot.hasdata 总是返回 false
    • @MohamedBorheneDhahri 在这种情况下,我建议您将快照与空值进行比较,例如 if(snapshot != null) { //Do your coding after this }。希望这会有所帮助
    【解决方案2】:

    您的错误是因为您试图将snapshot.error 放入Text 小部件中,而它不是String

    您可以通过将snapshot.error 转换为String 来解决此问题。检查下面的代码:它完美地工作:

    Text(snapshot.error.toString())
    

    我希望这会有所帮助。

    【讨论】:

    • 谢谢它可以解决这个问题,但我有一个新问题,即没有数据发送到快照,我的意思是有来自服务器的数据,但 snapshot.hasdata 总是返回 false
    • 不要忘记将答案标记为正确,如果对您有帮助,请点赞。
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2021-06-20
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多