Convert Single Api Reponse To A List Of Maps To Convert To Cards In Flutter
I have used the flutter cookbook to create a Future in order to convert a single Map into a card. However I want to do this with a list of Maps. I know I need to create a list and
Solution 1:
Your json doesn't actually return a json array, it actually returns a map with arbitrary key names like View1
, so we'll iterate that map. You need to hoist your FutureBuilder
up to the point where you can deal with the whole json at once, so at the page level. So CardPage
becomes
class CardPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API TEST')),
body: FutureBuilder<Map>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final Map<String, dynamic> data = snapshot.data;
final List<Container> cards = data.keys
.map((String s) => makeCard(Post.fromJson(data[s])))
.toList();
return ListView(
children: cards,
);
} else if (snapshot.hasError) {
return Text(snapshot.hasError.toString());
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
);
}
Container makeCard(Post post) {
return Container(
margin: EdgeInsets.all(20.0),
child: Text(post.appName),
);
}
Future<Map> fetchData() async {
final apiresponse =
await http.get('https://myriadapp-55adf.firebaseio.com/Views.json');
print(apiresponse.body);
return json.decode(apiresponse.body);
}
}
Post a Comment for "Convert Single Api Reponse To A List Of Maps To Convert To Cards In Flutter"