首页 > 解决方案 > 如何自动刷新 Stream Builder

问题描述

我有一个流构建器调用未来函数。我需要流生成器自动更新,但只有在我关闭并重新打开应用程序时才会刷新我该怎么办,请给我一个解决方案。我的代码:

StreamBuilder(
      stream: _databaseService.fetchNames(uid, 'Users').asStream(),
      builder: (context, AsyncSnapshot snapshot) {
        print(snapshot);
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Container(
              child: Center(
                  child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
              )),
            );
            break;
          case ConnectionState.active:
            return Container(
              child: Center(
                  child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
              )),
            );
            break;
          case ConnectionState.done:
            if (snapshot.data == 'No data') {
              return Container(
                child: Center(child: Text('No Chats')),
              );
            } else if (snapshot.data != 'No data') {
              List names = snapshot.data['collection'];
              return ListView(
                physics: BouncingScrollPhysics(),
                padding: EdgeInsets.only(top: 10),
                children: names
                    .map((e) => ListTile(
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ChatScreen(
                                      username: e['name'],
                                      receiverUid: e['id'])));
                        },
                        leading: CircleAvatar(
                          backgroundColor: secondaryColor,
                          child: Icon(
                            Icons.person,
                            color: Colors.white,
                          ),
                        ),
                        title: Padding(
                          padding: const EdgeInsets.only(top: 5.0),
                          child: Text(
                            e['name'].toString()[0].toUpperCase() +
                                e['name'].toString().substring(
                                      1,
                                    ),
                            style: TextStyle(fontSize: 25),
                          ),
                        )))
                    .toList(),
              );
            }
            break;
          case ConnectionState.none:
            return Container(
              child: Center(child: Text('No network')),
            );
            break;
        }
        return Container(
          child: Center(
              child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(secondaryColor),
          )),
        );
      },
    )

我的未来功能:

Future fetchNamesId(documentName, collectionName) async {
    Response response = await post(url,
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        },
        body: jsonEncode(
            {"documentName": documentName, "collectionName": collectionName}));
    if (response.body == "No data") {
      return "No data";
    }
    return jsonDecode(response.body);
  }

这是我得到的数据流,即 sanpshot.data:

{collection: [{id: 7hgIFK07xwhDGM82kJiQyGua36E3, name: bvc}, {id: Fgtf4ikE0QPifgknq5AVUdxCV2V2, name: vee}, {id: GbYWYJXcKwMmjsbx99QCvw0gWVL2, name: luu}, {id: egkH6fX7B2db54V1ALYWbKAXwG33, name: dia}]}

每当我在数据库中添加另一个值时,流不会自动刷新,我需要关闭并重新打开选项卡。

在代码中,我将其设为异步,但即使它没有自动更新。

请给我一个解决方案,我很震惊。提前致谢。

标签: flutterdartstream

解决方案


我建议使用提供者。您可以像这样将 StreamBuilder 包装到 StreamProvider :

  @override
  Widget build(BuildContext context) {
    return StreamProvider<whatever your stream returns>.value(
      value: your stream,
      child: StreamBuilder(...

推荐阅读