dart 未行程的例外状况:使用Firebase实时数据库聊天功能在dispose()后调用setState()

0ve6wy6x  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(79)

我收到此错误:

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: setState() called after dispose(): _EventChatScreenState#7c8b5(lifecycle state: defunct, not mounted)
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.
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.
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().
#0      State.setState.<anonymous closure> (package:flutter/src/wid<…>

然而,我调用setState的唯一地方是在initState中:

@override
  void initState() {
    super.initState();

    dbRef = dbInstance.ref("/events/");
    var query = dbRef!.child(widget.event.event.eventId);
    FirebaseList(
      query: query,
      onChildAdded: (index, snapshot) {
        Map<dynamic, dynamic> childMap = snapshot.value as dynamic;
        ChatMessage newChatMessage = ChatMessage(
          chatMessageId: snapshot.key.toString(),
          userId: childMap["userId"],
          displayName: childMap["displayName"],
          message: childMap["message"],
          datetime: childMap["datetime"],
        );

        setState(() {
          chatMessages.add(newChatMessage);
        });
      },
    );
    _messageFieldController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _messageFieldController.dispose();
  }

我不确定为什么会发生这种情况,但是我包含了dispose方法,因为错误引用了它。
值得注意的是,我这样做是为了使屏幕滚动到聊天消息的底部,这些消息是使用ListView.builder显示的

void scrollToBottom() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userProvider);
    if (chatMessages.isNotEmpty) {
      scrollToBottom();
    }

如果我删除上面的代码,问题似乎就消失了

jhdbpxl9

jhdbpxl91#

"而不是这个"

@override
  void dispose() {
    super.dispose();
    _messageFieldController.dispose();
  }

"试试这个"

@override
  void dispose() {
    _messageFieldController.dispose();
    super.dispose();
  }

相关问题