简体   繁体   中英

ListView.seperated displaying Only after a Hot Reload

I have called the getRecords function in initState . The listview only displays after I hot reload. I tried putting it under setState , but it didn't help.

void getRecords() async {
final records =
    await Firestore.instance.collection('records').getDocuments();
for (var record in records.documents) {
  if (record.data['email'] == newEmail) {
    int len = record.data['requestEmail'].length;
    for (int i = 0; i < len; i++) {
      if(record.data['requestEmail'][i] != newEmail){
        names.add(record.data['requestName'][i]);
        emails.add(record.data['requestEmail'][i]);
      }
      else
        continue;
    }
  }
}
print(names);

body: ListView.separated(
    padding: const EdgeInsets.all(8),
    itemCount: names.length,
    itemBuilder: (BuildContext context, int index) {
      return Card(
        color: Colors.white,
        child: ListTile(
          onTap: () {},
          title: Text('${names[index]}'),
        ),
      );
    },
    separatorBuilder: (BuildContext context, int index) => const Divider(),
  ),

This is happening because getting data from firebase is async task, so it takes time. Meanwhile build method build the widget without data, so when you get data you have to call setState to build listview with actual data.

Moreover, i also like to suggest that you can use futurebuilder or streambuilder when you are working with async.

void getRecords() async {
final records =
    await Firestore.instance.collection('records').getDocuments();
for (var record in records.documents) {
  if (record.data['email'] == newEmail) {
    int len = record.data['requestEmail'].length;
    for (int i = 0; i < len; i++) {
      if(record.data['requestEmail'][i] != newEmail){
        names.add(record.data['requestName'][i]);
        emails.add(record.data['requestEmail'][i]);
      }
      else
        continue;
    }
  }
  setState(() {});  // added line
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM