Home > Software engineering >  How do I join Keys and Values. Flutter/Dart
How do I join Keys and Values. Flutter/Dart

Time:07-28

This is my code right now :

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){
                    values.add(item.keys.map((e)  => e.toString()).join("\n"));
                    values.add(item.values.map((e) => e.toString()).join("\n"));
                  }
                  await WriteCache.setListString(key: 'cache4', value: values);

How do I combine the keys and value so that my list is in the format of "key : value" instead of just value

CodePudding user response:

You can run a nested loop

for(final item in incidentList){
 String groupedElement = "";
   for(var innerItem in item.entries)
   {
      groupedElement  = "${innerItem.key}:${innerItem.value},";
   }
   value.add(groupedElement);
}

CodePudding user response:

You can Not shure what format you want, but is sound like JSON. So if you want JSON

You can just replace:

await WriteCache.setListString(key: 'cache4', value: json.encode(incidentList));

Don't forget to import dart:convert:

import 'dart:convert';

And remove:

final List<String> values =  [];
for(final item in incidentList){
    values.add(item.keys.map((e)  => e.toString()).join("\n"));
    values.add(item.values.map((e) => e.toString()).join("\n"));
}

ATTENTION, this will return a String, not a list of String

For retrieveing a Map<String, dynamic> from your save data, just do:

final jsonData = json.decode(savedJsonStr);
  • Related