如何在 Flutter 中自动刷新 listView?

how can I auto refresh listView in Flutter?

我实现了 listView 来显示数据,我将数据保存到 Sqflite Database,从数据库中获取并显示到列表视图中。保存数据后,我 pop 从表单字段页面到 listView 页面,但我的 ListView 没有更新,我需要返回然后打开 listView 才能看到新记录。

  List<SubjectModel> list;
  int count = 0;
  SubjectModel subjectModel;

  @override
  Widget build(BuildContext context) {
    if (list == null) {
      list = List<SubjectModel>();
      updateListView();
    }
    return Scaffold(
      appBar: AppBar(
        title: Text('Subject'),
      ),
      floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.purple,
          child: Icon(Icons.add),
          onPressed: () {
            Navigator.push(context,
                new MaterialPageRoute<void>(builder: (context) {
                  return new CreateTask(SubjectModel('', '', '', '', '', '', ''),'Add Subject');
                }));
          }),
      body: getSubListView()
    );
  }

  ListView getSubListView(){
    return ListView.builder(
        itemCount: count,
        itemBuilder: (BuildContext context, int position){
          return Card(
            color: Colors.white,
            elevation: 2.0,
            child: Column(
              children: <Widget>[
                ListTile(
                  title: Text(this.list[position].subject),
                  onLongPress: () => navigateToDetail(this.list[position],'Edit Subject'),
                )
              ],
            ),
          );
        }
    );
  }
}

每当您想重建任何东西(本例中是您的 listView)时,都必须调用 setState()。

我要补充:

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    setState(() {
      updateListView();
    });
  }