Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a dynamic list in Flutter?

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.
    ));
  }
}
like image 497
Patrioticcow Avatar asked Dec 15 '17 06:12

Patrioticcow


People also ask

How do you make a list dynamically in flutter?

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.

How do you convert a list list to dynamic string in flutter?

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.


1 Answers

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
        ));

  }

}
like image 121
Hemanth Raj Avatar answered Oct 10 '22 16:10

Hemanth Raj