Issue
I have a nested array that i'm trying to get all the records in it's interests
but i'm getting error doing that, kind of new to this , below is the array list
{
interests:
[
{
id: 1,
name: Fashion,
},
{
id: 2,
name: Art,
}
]
}
How do i get the list of all ids and names at once from the interest...
i tried
var data = convert.json.decode(response.body);
print(data["interests"][0]["name"].toString());
if (response.statusCode == 200) {
streamControllerforInterestList.add(data);
}
and this only gives the first, when i use 1, the second. but i can't make it empty... please help. thanks and i'm trying to send it into a stream builder below
StreamBuilder<List>(
stream: streamControllerforInterestList.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return MultiSelectChipField<Interest?>(
items: [
for (Map document in snapshot.data)
MultiSelectItem<Interest>(
(document[["id"]]), document[["name"]])
].toList(),
icon: const Icon(
Icons.clear,
color: Colors.black,
),
showHeader: false,
scroll: false,
// title: const Text("Interests"),
// headerColor: Colors.blue.withOpacity(0.5),
decoration: const BoxDecoration(),
selectedChipColor: HexColor('#FFB7E1').withOpacity(0.5),
selectedTextStyle:
const TextStyle(color: Color.fromARGB(255, 0, 0, 0)),
onTap: (values) {
//_selectedAnimals4 = values;
},
);
}
return Container(
padding: const EdgeInsets.only(top: 20),
child: Row(
children: const [
Text(
' Loading Interests...',
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
],
),
);
},
),
Solution
Try this model class.
class ModelClass {
final int id;
final String name;
ModelClass({
required this.id,
required this.name,
});
factory ModelClass.fromMap(Map<String, dynamic> map) {
return ModelClass(
id: map['id']?.toInt() ?? 0,
name: map['name'] ?? '',
);
}
@override
String toString() => 'ModelClass(id: $id, name: $name)';
}
And get data
final items = data["interests"];
// this `result` contains all the item.
final result = items?.map((e) => ModelClass.fromMap(e)).toList() ?? [];
for (final r in result) {
print(r.toString());
}
Answered By - Yeasin Sheikh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.