Here is my List of maps. But I want to convert these to string.
[{tid: 20210813, title: hello3, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549e}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549d}, {tid: 20210814, title: hello4, description: hello good evening every one, _id: 62ecc3f047ff077fe8d4549f}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ecc3f047ff077fe8d454a0}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ece09647ff077fe8d454e6}, {tid: 20210812, title: hello, description: hello good evening every one, _id: 62ece09647ff077fe8d454e9}, {tid: 20210813, title: 2766767236, description: hello good evening every one, _id: 62ece09647ff077fe8d454e7}, {tid: 20210814, title: hello4, description: hello good evening every one, _id: 62ece09647ff077fe8d454e8}]
CodePudding user response:
You can use this model class
import 'dart:convert';
class ModelClass {
final int? tid;
final String? title;
final String? description;
final String? sId;
ModelClass({
this.tid,
this.title,
this.description,
this.sId,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
if (tid != null) {
result.addAll({'tid': tid});
}
if (title != null) {
result.addAll({'title': title});
}
if (description != null) {
result.addAll({'description': description});
}
if (sId != null) {
result.addAll({'sId': sId});
}
return result;
}
factory ModelClass.fromMap(Map<String, dynamic> map) {
return ModelClass(
tid: map['tid']?.toInt(),
title: map['title'],
description: map['description'],
sId: map['sId'],
);
}
String toJson() => json.encode(toMap());
factory ModelClass.fromJson(String source) =>
ModelClass.fromMap(json.decode(source));
}
And to get items
final data = jsonDecode(response.body) as List;
return data.map((e) => ModelClass.fromMap(e)).toList();
CodePudding user response:
You need to decode the response into json before getting values
getAllTodos(BuildContext context) async {
try {
var todos = await _homeRepo.getAllTodos(context);
return todoFromJson(jsonDecode(todos));
}
catch (e) {
Fluttertoast.showToast(msg: e.toString()); return null;
}
}
CodePudding user response:
You didn't phrase your question very clearly, but here's some speculation.
First, the map itself has the wrong structure. This is what the correct one looks like:
List myList = [
{
'tid': 20210813,
'title': 'hello3',
'description': 'hello good evening every one',
'_id': '62ecc3f047ff077fe8d4549e'
},
{}
];
You can convert everything to a string with a simple command toString(). Do a for and call toString().
main() {
String str = myList.toString(); // or all
for (final m in myList ){
m.toString();
}
}
However, I assume that in your case you need to convert the maps into a model class by presenting a toJson()/fromJson() or toString()/fromString() method for conversions.