简体   繁体   English

如何从 snapshot.data [index] 中的数据创建 map。 颤振/飞镖

[英]How do I create a map from data inside snapshot.data[index]. Flutter/Dart

I am trying to access and use values that are In my snapshot.data[index]我正在尝试访问和使用我的 snapshot.data[index] 中的值

What I am printing using print(snapshot.data[index]):我使用 print(snapshot.data[index]) 打印的内容:

I/flutter (11316): Code : LE-0000000002
I/flutter (11316): Description : test_01
I/flutter (11316): Organisation Unit : 01_01_04_01_SA - Shah Alam
I/flutter (11316): Date Reported : 18/09/2020
I/flutter (11316): Status : LE110 - Pending Approval
I/flutter (11316): RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}

this is the code thats feeding data into the snapshot这是将数据输入快照的代码

List<Map<String, dynamic>> incidentList = [
                    for (final json in listNode.map((x) => x.toJson()))
                      {
                        'Code': json['field'][0]['field_value'],
                        'Description': json['field'][1]['field_value'],
                        'Organisation Unit': json['field'][2]['field_value'],
                        'Date Reported': json['field'][3]['field_value'],
                        'Status': json['field'][4]['field_value'],
                        'RunHyperlink' : json['run_hyperlink']
                      }
                  ];


                  final List<String> values =  [];
                  for(final item in incidentList){
                    String groupedElement = "";
                    for(var innerItem in item.entries)
                    {
                      groupedElement += "${innerItem.key} : ${innerItem.value}\n";
                    }
                    values.add(groupedElement);
                  }

                  await WriteCache.setListString(key: 'cache4', value: values);

and this is the future builder:这是未来的建设者:

FutureBuilder(
              future: ReadCache.getStringList(key: 'cache4'),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: ListTile(
                            onTap: () {

                              print(snapshot.data[index]);
                            },
                            title: Padding(
                              padding: const EdgeInsets.only(top: 10),
                              child: Text(snapshot.data[index],
                                  style: GoogleFonts.poppins(
                                    textStyle: const TextStyle(
                                      fontWeight: FontWeight.normal,
                                      fontSize: 20,
                                    ),
                                  )),
                            ),
                            tileColor: Colors.blueGrey[200],
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      });
                } else {
                  return const Text("No Data");
                }
              },
            ),

I want to use the "id: value" that is being displayed.我想使用正在显示的“id:value”。 I understand that need to create a map to do so but am unsure of how to go about it.我知道需要创建一个 map 这样做,但我不确定如何 go 关于它。 Can anyone help me create this map?谁能帮我创建这个 map?

The reason why I need to access and use the "id: value" is that I need to pass whatever value is in the "id" to a queryparameter.我需要访问和使用“id: value”的原因是我需要将“id”中的任何值传递给查询参数。

Thanks!谢谢!

At least for a AsyncSnapshot from firestore should be able to access the id just by treating the snapshot.data as a map:至少对于来自 firestore 的 AsyncSnapshot 应该能够通过将 snapshot.data 视为 map 来访问 id:

int id = snapshot.data[index]['id']

otherwise you could cast it to a Map like that:否则,您可以将其转换为 Map ,如下所示:

Map snapshotData = snapshot.data[index] as Map<String, int>

try this尝试这个

   List data = snapshot.data!

you can access id by您可以通过以下方式访问 id

data[index].id

Maybe it makes sense to generate models to simplify working with data?生成模型以简化数据处理是否有意义?
The models below were generated from YAML model descriptions during build process:以下模型是在构建过程中从 YAML model 描述生成的:

lib/stackoverflow.json.dart

class Incident {
  Incident(
      {required this.code,
      required this.description,
      required this.organisationUnit,
      required this.dateReported,
      required this.status,
      required this.runHyperlink});

  factory Incident.fromJson(Map json) {
    return Incident(
      code: json['Code'] == null ? '' : json['Code'] as String,
      description:
          json['Description'] == null ? '' : json['Description'] as String,
      organisationUnit: json['Organisation Unit'] == null
          ? ''
          : json['Organisation Unit'] as String,
      dateReported:
          json['Date Reported'] == null ? '' : json['Date Reported'] as String,
      status: json['Status'] == null ? '' : json['Status'] as String,
      runHyperlink: RunHyperlink.fromJson(json['RunHyperlink'] as Map),
    );
  }

  final String code;

  final String description;

  final String organisationUnit;

  final String dateReported;

  final String status;

  final RunHyperlink runHyperlink;

  static List<Incident> fromJsonList(List json) {
    return json.map((e) => Incident.fromJson(e as Map)).toList();
  }

  Map<String, dynamic> toJson() {
    return {
      'Code': code,
      'Description': description,
      'Organisation Unit': organisationUnit,
      'Date Reported': dateReported,
      'Status': status,
      'RunHyperlink': runHyperlink.toJson(),
    };
  }

  static List<Map<String, dynamic>> toJsonList(List<Incident> list) {
    return list.map((e) => e.toJson()).toList();
  }
}

class RunHyperlink {
  RunHyperlink({required this.classId, required this.id, required this.madKey});

  factory RunHyperlink.fromJson(Map json) {
    return RunHyperlink(
      classId: json['classid'] == null ? 0 : json['classid'] as int,
      id: json['id'] == null ? 0 : json['id'] as int,
      madKey: json['mad_key'] == null ? 0 : json['mad_key'] as int,
    );
  }

  final int classId;

  final int id;

  final int madKey;

  static List<RunHyperlink> fromJsonList(List json) {
    return json.map((e) => RunHyperlink.fromJson(e as Map)).toList();
  }

  Map<String, dynamic> toJson() {
    return {
      'classid': classId,
      'id': id,
      'mad_key': madKey,
    };
  }

  static List<Map<String, dynamic>> toJsonList(List<RunHyperlink> list) {
    return list.map((e) => e.toJson()).toList();
  }
}

lib/stackoverflow.json.yaml

classes:
  Incident:
    fields:
      code:
        type: String
        alias: Code
      description:
        type: String
        alias: Description
      organisationUnit:
        type: String
        alias: Organisation Unit
      dateReported:
        type: String
        alias: Date Reported
      status:
        type: String
        alias: Status
      runHyperlink:
        type: RunHyperlink
        alias: RunHyperlink

  RunHyperlink:
    fields:
      classId:
        type: int
        alias: classid
      id: int
      madKey:
        type: int
        alias: mad_key

pubspec.yaml

dev_dependencies:
  build_runner: any
  object_serializer: ^0.3.6

dart run build_runner build

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问 snapshot.data[index] 中的值。 颤振/飞镖 - How do I access value in snapshot.data[index] . Flutter/Dart 我正在尝试访问先前定义的发送到 snapshot.data 的变量? 颤振/飞镖 - I am trying to access previously defined variable sent to snapshot.data? Flutter/Dart 如何使用存储在 FutureBuilder 的 snapshot.data 中的 JSON 数据(无类)? - How do I use JSON data stored in FutureBuilder's snapshot.data (without class)? 有没有办法在 Dart / Flutter (REST) 中根据对象值显示快照数据? - Is there a way to to show snapshot data based on object value in Dart / Flutter (REST)? 我很难使用 dart/flutter 从 json 映射中的嵌套对象获取数据 - I am having a hard time getting data from an nested object in a json map using dart/flutter Flutter:如何访问 Map 中的数组数据? - Flutter: How to access array data inside a Map? 我将如何在 Dart 中访问此 JSON 数据以用于 Flutter 项目? - How would I access this JSON data in Dart for a flutter project? 如何在颤振/飞镖中删除嵌套对象中的详细数据? - How can I delete detail data in nested objects in flutter/dart? Flutter 快照数据为空 - Flutter snapshot data is empty 如何在反应 js 中 map 来自 JSON 文件中的数组的数据? - How do I map the data from an array inside an JSON file in react js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM