ListView.seperated仅在热重载后显示

时间:2020-04-12 11:58:45

标签: flutter

我在initState中调用了getRecords函数。 仅在我重新加载后显示列表视图。我尝试将其放在setState下,但没有帮助。

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(),
  ),

1 个答案:

答案 0 :(得分:0)

之所以发生这种情况是因为从Firebase获取数据是异步任务,因此需要时间。同时,构建方法会在不包含数据的情况下构建窗口小部件,因此,在获取数据时,必须调用setState来使用实际数据构建列表视图。

此外,我还建议您在使用异步时可以使用 futurebuilder streambuilder

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
}