How to build a dynamic list in Flutter?
You can use the setState
to rebuild the UI.
Example:
class TestList extends StatefulWidget { final Future<List> quiz; TestList({this.quiz}); @override _TestListState createState() => new _TestListState();}class _TestListState extends State<TestList> { bool loading = true; _TestListState(){ widget.quiz.then((List value) { // loop through the json object for (var i = 0; i < value.length; i++) { // add the ListTile to an array listArray.add(new ListTile(title: new Text(value[i].name)); } //use setState to refresh UI setState((){ loading = false; }); }); } @override Widget build(BuildContext context) { List<Widget> listArray = []; return new Container( child: new ListView( children: loading?[]:listArray // when the state of loading changes from true to false, it'll force this widget to reload )); }}
You can use FutureBuilder to help with the widget states:
new FutureBuilder<List>( future: widget.quiz, builder: (BuildContext context, AsyncSnapshot<List> snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: return new Text('Waiting to start'); case ConnectionState.waiting: return new Text('Loading...'); default: if (snapshot.hasError) { return new Text('Error: ${snapshot.error}'); } else { return new ListView.builder( itemBuilder: (context, index) => new Text(snapshot.data[index].name), itemCount: snapshot.data.length); } } },)
Basically, it notifies the method specified on builder depending on the future state. Once the future received a value and is not an error, you can use ListView.builder to make the list, this is a convenience method to create the list when all items are of the same type.
More info at https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html