Using value returned in function to create a listview flutter

Asked

Viewed 73 times

-1

I have a function that accesses the Firestore and returns a list, when I click on a button this function is called and should create a lisrviwerbuilder(). But I don’t know why he doesn’t create.

    readdados() async {
    QuerySnapshot snapshot = await Firestore.instance.collection('cliente').getDocuments();
    snapshot.documents.forEach((d) {listanomes.add(d.data['nome']);
    });
    return listanomes;
  }     
    RaisedButton(onPressed: () {
                      readdados();
                    }),
                  ],
                ),
              ),
              Expanded(
                  child: ListView.builder(
                      padding: EdgeInsets.only(top: 10),
                      itemCount: listanomes.length,
                      itemBuilder: (context, index) {
                        return ListTile(title: Text(listanomes[index]));
                      })),

1 answer

1


If you are using a StatefulWidget modify your button click as follows:

readdados() async {
  QuerySnapshot snapshot = await Firestore.instance.collection('cliente').getDocuments();
    snapshot.documents.forEach((d) {listanomes.add(d.data['nome']);
  });

  return listanomes;
} 

RaisedButton(
    onPressed: () {
      setState(() async{
        readdados();
      });
    }),
Expanded(
  child: ListView.builder(
      padding: EdgeInsets.only(top: 10),
      itemCount: listanomes.length,
      itemBuilder: (context, index) {
        return ListTile(title: Text(listanomes[index]));
      })
),

Explanation

Using the setState((){}) you indicate to Flutter that it should redesign this widget, so your list will be changed.

Tip

How are you working with the Firebase you can use Streams to make your app "automatic", search for StreamBuilder + Firebase.

Note: If this does not solve your problem, Edith your question and put more information, more code would be perfect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.