I have this widget attached to a Scaffold
body. The widget gets a async
method that returns a json object.
I want to build a list, dynamically, from that json object. The problem is that the screen is empty.. For some reason this widget needs to refresh itself when the list is ready or something like that.
Any ideas?
class TestList extends StatelessWidget {
final quiz;
TestList({this.quiz});
@override
Widget build(BuildContext context) {
var listArray = [];
this.quiz.then((List value) { // this is a json object
// 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));
}
});
return new Container(
child: new ListView(
children: listArray // add the list here.
));
}
}
We can use ListView. builder(..) in Stateless Widgets if we want to display dynamic (different) contents every time the widget is loaded within an application. With Stateful widgets, it can change the contents of the screen dynamically.
In dart and flutter, this example converts a list of dynamic types to a list of Strings. map() is used to iterate over a list of dynamic strings. To convert each element in the map to a String, toString() is used. Finally, use the toList() method to return a list.
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
));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With