list - 无法在 flutter 中使用 socket.io 数据更新 ListView ?

标签 list flutter dart socket.io setstate

我正在使用 node.js 开发后端和 expressMongoDBsocket.io在前端,我使用 flutterdart .

我正在使用 emit将数据从后端发送到 flutter应用程序,它工作正常,我可以收到消息,所以问题不在后端。

当我收到该消息时,我想将其添加到列表中,然后 setstate 刷新构建方法以重新构建构建方法,但它失败并给了我该错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: setState() called after dispose(): _NewsState#a696c(lifecycle state: defunct, not mounted)
E/flutter (11883): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter (11883): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (11883): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().

这是我的代码片段,用于监听来自后端的事件:

Provider.of<IoProvider>(context).globalSocket.connect();
    Provider.of<IoProvider>(context).globalSocket.on('posts', (data) {
      if (data['action'] == 'add') {
        setState(() {
          postData.add(data['data']);
        });
      }
      print('--emit--');
    });

我在构建方法中使用它,并且我在状态类的顶部声明了 postData 列表。

我还在 init state 方法中使用 future 函数从后端获取数据,然后 setstate 使 postData 等于来自后端的响应数据并成功。

代码片段:

Future getPosts() async {
    var data = await PostController().fetchPosts();

    if (data['success'] == true) {
      setState(() {
        postData = data['posts'];
      });
    }
  }

在 initState 内部:

@override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      getPosts(context);
    });
      _editingController = TextEditingController();
  }

内部构建方法:

ListView.builder(
    itemCount: postData.length,
    itemBuilder: (context , index) => PostView(postData[index]),
  );

更新

经过测试,我发现问题在用户第一次导航到该屏幕时没有发生,但在其他时候它失败了。

但是如何解决呢?

最佳答案

经过太多搜索,我发现问题是由 flutter 本身引起的,因为我使用的是带有四个屏幕的底部导航栏,并且每次我在一段时间后访问它们时都会想起 initstate。
最后,我能够通过使用索引堆栈小部件来解决这个问题。
谢谢,

关于list - 无法在 flutter 中使用 socket.io 数据更新 ListView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61056481/

相关文章:

flutter - flutter 中的 ListView 涟漪效应

dart - 如何组织我的 Dart 项目

json - R将json转换为列表到data.table

Java 列表按引用或值传递

python - 打印字典变量名列表

flutter - 如何在 flutter App 上叠加一个小部件?

r - 如何从相当于 R 的 Python 数据帧列表中选择特定数据帧?

android - 在运行时更改应用程序主题

list - Dart :检查列表列表中的项目

android - 如何在 Flutter 中制作水平数字选择器小部件?