【问题标题】:Getting data from json by key, not index, with flutter使用颤振通过键而不是索引从json获取数据
【发布时间】:2022-01-10 20:56:10
【问题描述】:

我有一个这种结构的 json 表; {id: 1, deviceid: 1, devicenumber: 11, number1: 1, number2: 2, number3: 3, number4: 0, number5: 5, date: 0000-00-00 00:00:00}

通过这段代码,我可以根据索引从json表中拉取数据。但我想要的是提取所有 json 数据并在所有键中搜索。

因为我并不总是知道索引号,但 deviceid 键号始终可用。这就是为什么要将捕获的数据与我拥有的数据进行匹配并获取其他正确信息的原因。

【问题讨论】:

    标签: json flutter


    【解决方案1】:

    我假设您将使用 FutureBuilder,所以我的回答是基于此,但您应该从中了解基础知识

    我会先为你的 json 数据创建一个类

    Class ClassName {
    final String? testText
    
    ClassName({this.testText});
    
    factory ClassName.fromJson(Map<String, dynamic> json) {
      return ClassName(testText: json['test_text']);
     }
    }
    

    然后获取 url 并在您的主窗口小部件上对其进行解析,该获取应该如下所示:

    Future<ClassName>? futureData;
    
    Future<ClassName> fetchData() async {
    final response = await http.get(Uri.parse(
        url));
    
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      return ClassName.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Error');
    }
      }
    
      @override
      void initState() {
        futureData = fetchData();
        super.initState();
        }}
    

    稍后在使用 FutureBuilder 时,您可以将此数据用作未来

    FutureBuilder<ClassName>(
      future: futureData,
      builder: (context, snapshot) {
        if(snapshot.hasData) {
          return Container(
            child: Text(snapshot.data!.testText),)}},
    

    【讨论】:

    • builder: (context, snapshot) { 在方括号中不断出现错误。 type'List' 不是'Map' 类型的子类型,我收到错误消息
    • @user 我建议看看这个link 应该可以解决你的问题
    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 2021-03-26
    • 2019-04-20
    • 2020-11-17
    • 2021-03-21
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多