繁体   English   中英

Flutter NoSuchMethodError:在 null 上调用了方法“toDate”

[英]Flutter NoSuchMethodError: The method 'toDate' was called on null

抛出异常: NoSuchMethodError: The method 'toDate' was called on null

例外:

══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
The following assertion was thrown while dispatching notifications for TextEditingController:
setState() called after dispose(): _CommentsState#74ccc(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().

When the exception was thrown, this was the stack:
#0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1137:9)
#1      State.setState (package:flutter/src/widgets/framework.dart:1172:6)
#2      _CommentsState.initState.<anonymous closure> (package:anime_space_app/widgets/comments.dart:33:41)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:308:24)
#4      ValueNotifier.value= (package:flutter/src/foundation/change_notifier.dart:412:5)
#5      TextEditingController.value= (package:flutter/src/widgets/editable_text.dart:154:11)
#6      EditableTextState._value= (package:flutter/src/widgets/editable_text.dart:2161:23)
#7      EditableTextState._formatAndSetValue (package:flutter/src/widgets/editable_text.dart:2540:5)
#8      EditableTextState.userUpdateTextEditingValue (package:flutter/src/widgets/editable_text.dart:2769:5)
#9      RenderEditable._setTextEditingValue (package:flutter/src/rendering/editable.dart:735:27)
#10     RenderEditable._setSelection (package:flutter/src/rendering/editable.dart:755:5)
#11     RenderEditable.selectPositionAt (package:flutter/src/rendering/editable.dart:1974:5)
#12     RenderEditable.selectPosition (package:flutter/src/rendering/editable.dart:1950:5)
#13     TextSelectionGestureDetectorBuilder.onSingleTapUp (package:flutter/src/widgets/text_selection.dart:1158:26)  
#14     _TextFieldSelectionGestureDetectorBuilder.onSingleTapUp (package:flutter/src/material/text_field.dart:89:11) 
#15     _TextSelectionGestureDetectorState._handleTapUp (package:flutter/src/widgets/text_selection.dart:1511:29)    
#16     TapGestureRecognizer.handleTapUp.<anonymous closure> (package:flutter/src/gestures/tap.dart:611:57)
#17     GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#18     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:611:11)
#19     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:298:5)
#20     BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:269:7)
#21     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
#22     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:443:20)
#23     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#24     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#25     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#26     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#27     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#28     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#32     _invoke1 (dart:ui/hooks.dart:170:10)
#33     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#34     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)

The TextEditingController sending notification was:
  TextEditingController#722ea(TextEditingValue(text: ┤├, selection: TextSelection.collapsed(offset:
  0, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end:
  -1)))
════════════════════════════════════════════════════════════════════════════════════════════════════
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
V/InputMethodManager(21258): Starting input: tba=site.animslash.app ic=io.flutter.plugin.editing.InputConnectionAdaptor@6a46c51 mNaviBarColor -15130582 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager(21258): startInputInner - Id : 0
I/InputMethodManager(21258): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(21258): Input channel constructed: fd=159
D/InputTransport(21258): Input channel destroyed: fd=187
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
D/ViewRootImpl@d406a90[MainActivity](21258): MSG_RESIZED: frame=Rect(0, 0 - 1440, 2960) ci=Rect(0, 84 - 0, 1032) vi=Rect(0, 84 - 0, 1032) or=١
D/ViewRootImpl@d406a90[MainActivity](21258): Relayout returned: old=[0,0][1440,2960] new=[0,0][1440,2960] result=0x1 
surface={valid=true 497100464128} changed=false
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not  
mounted)

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not  
mounted)
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not  
mounted)
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
D/InputMethodManager(21258): SSI - flag : 0 Pid : 21258 view : site.animslash.app
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not  
mounted)
D/ViewRootImpl@d406a90[MainActivity](21258): ViewPostIme pointer 0
D/ViewRootImpl@d406a90[MainActivity](21258): ViewPostIme pointer 1

Another exception was thrown: NoSuchMethodError: The method 'toDate' was called on null.

Another exception was thrown: setState() called after dispose(): _CommentsState#74ccc(lifecycle state: defunct, not  
mounted)
I/TextInputPlugin(21258): Composing region changed by the framework. Restarting the input method.
D/InputMethodManager(21258): prepareNavigationBarInfo() DecorView@456f89[MainActivity]
D/InputMethodManager(21258): getNavigationBarColor() -15130582
V/InputMethodManager(21258): Starting input: tba=site.animslash.app ic=io.flutter.plugin.editing.InputConnectionAdaptor@67a2caf mNaviBarColor -15130582 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false
D/InputMethodManager(21258): startInputInner - Id : 0
I/InputMethodManager(21258): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(21258): Input channel constructed: fd=160
D/InputTransport(21258): Input channel destroyed: fd=159
W/IInputConnectionWrapper(21258): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(21258): getTextBeforeCursor on inactive InputConnection
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
I/chatty  (21258): uid=10334(site.animslash.app) identical 2 lines
E/SpannableStringBuilder(21258): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

Another exception was thrown: NoSuchMethodError: The method 'toDate' was called on null.

源代码:

class Comments extends StatefulWidget {   Comments({this.title});   final String? title;   @override   State<Comments> createState() =>
_CommentsState(); }

class _CommentsState extends State<Comments> {   @override   void initState() {
    getcurrentuser();
    CommentController.addListener(() => setState(() {}));

    super.initState();   }

  void getcurrentuser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        signinUser = user;
        print(signinUser.email);
      }
    } catch (e) {
      print(e);
    }   }

  @override   Widget build(BuildContext context) {
    final CmID = FirebaseFirestore.instance
        .collection('Comments')
        .doc('${widget.title}')
        .collection('Comments')
        .doc()
        .id;
    return Scaffold(
      backgroundColor: kPrimaryColor,
      body: SafeArea(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              decoration: BoxDecoration(
                color: kBackgroundColor,
                border: Border(
                  top: BorderSide(
                    color: kBackgroundColor,
                    width: 2,
                  ),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: CommentController,
                        validator: (val) {
                          if (val!.isEmpty || val.length <= 2) {
                            return "الرجاء ادخال تعليق صحيح";
                          } else {
                            return null;
                          }
                        },
                        style: TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.comment, color: Colors.white),
                          labelText: 'ادخل تعليقك',
                          labelStyle: TextStyle(color: Colors.white),
                          prefixStyle: TextStyle(color: Colors.white),
                          iconColor: Colors.blue,
                          contentPadding: EdgeInsets.symmetric(
                            vertical: 10,
                            horizontal: 20,
                          ),
                          prefixIconColor: Colors.blue,
                          suffixIcon: CommentController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  splashRadius: 22,
                                  onPressed: () => CommentController.clear(),
                                  icon: Icon(Icons.close),
                                ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                          ),
                          focusColor: Colors.blue,
                          hoverColor: Colors.blue,
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                    TextButton(
                      style: ButtonStyle(),
                      onPressed: () async {
                        if (CommentController.text.isEmpty ||
                            CommentController.text.length < 3) {
                          Fluttertoast.showToast(
                            msg: 'يجب على تعليقك ان يكون حرفين او اكثر',
                            backgroundColor: kBackgroundColor,
                          );
                        } else {
                          final commentid = FirebaseFirestore.instance
                              .collection('Comments')
                              .doc(widget.title)
                              .collection('Comments')
                              .doc();

                          final json = {
                            'id': commentid.id,
                            'sender': signinUser.displayName,
                            'img': signinUser.photoURL,
                            'time': FieldValue.serverTimestamp(),
                            'text': CommentController.text,
                          };

                          await commentid.set(json);

                          CommentController.clear();
                        }
                      },
                      child: Text(
                        'ارسال',
                        style: TextStyle(
                          color: Colors.blue,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          CommentsStreamBuilder(
            title: '${widget.title}',
          ),
        ],
      )),
    );   } }



class CommentsLine extends StatelessWidget {
  CommentsLine(
      {required this.time,
      this.title,
      this.img,
      this.text,
      this.sender,
      required this.isMe});
  final String? title;
  final Timestamp time;
  final String? sender;
  final String? text;
  final bool isMe;

  final String? img;

  @override
  Widget build(BuildContext context) {
    DateTime minAgo = DateTime.now().subtract(const Duration(minutes: 1));
    DateTime secAgo = DateTime.now().subtract(const Duration(seconds: 1));
    DateTime dayAgo = DateTime.now().subtract(const Duration(days: 1));
    DateTime monAgo = DateTime.now().subtract(const Duration(days: 30));
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8), color: kBackgroundColor),
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      '$sender',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      timeago.format(time.toDate(), locale: 'ar'),
                      style: TextStyle(color: Colors.white70, fontSize: 12),
                    )
                  ],
                ),
                SizedBox(
                  width: 10,
                ),
                CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage('$img'),
                ),
              ],
            ),
            SizedBox(
              height: 8,
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '$text',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CommentsStreamBuilder extends StatelessWidget {
  CommentsStreamBuilder({this.title});
  final String? title;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore
          .collection('Comments')
          .doc('$title')
          .collection('Comments')
          .orderBy('time')
          .snapshots(),
      builder: (context, snapshot) {
        List<CommentsLine> commentsWidget = [];

        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: kBackgroundColor,
            ),
          );
        }
        if (snapshot.data?.docs.isEmpty != false) {
          return Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/cry.gif',
                  height: 110,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  "لاتوجد تعليقات",
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          );
        }
        final messages = snapshot.data!.docs.reversed;
        for (var message in messages) {
          final messagetext = message.get('text');
          final messgaesender = message.get('sender');
          final messgaeimg = message.get('img');
          final datatime = message.get('time');
          final currentUser = signinUser.displayName;

          final commentWidget = CommentsLine(
            sender: messgaesender,
            time: datatime,
            img: messgaeimg,
            text: messagetext,
            isMe: currentUser == messgaesender,
            title: title,
          );
          commentsWidget.add(commentWidget);
        }

        return Expanded(
          child: ListView(
            reverse: false,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
            children: commentsWidget,
          ),
        );
      },
    );
  }
}

您需要检查time是否为 null。 检查下面的代码。

class Comments extends StatefulWidget {   Comments({this.title});   final String? title;   @override   State<Comments> createState() =>
_CommentsState(); }

class _CommentsState extends State<Comments> {   @override   void initState() {
    getcurrentuser();
    CommentController.addListener(() => setState(() {}));

    super.initState();   }

  void getcurrentuser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        signinUser = user;
        print(signinUser.email);
      }
    } catch (e) {
      print(e);
    }   }

  @override   Widget build(BuildContext context) {
    final CmID = FirebaseFirestore.instance
        .collection('Comments')
        .doc('${widget.title}')
        .collection('Comments')
        .doc()
        .id;
    return Scaffold(
      backgroundColor: kPrimaryColor,
      body: SafeArea(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              decoration: BoxDecoration(
                color: kBackgroundColor,
                border: Border(
                  top: BorderSide(
                    color: kBackgroundColor,
                    width: 2,
                  ),
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: CommentController,
                        validator: (val) {
                          if (val!.isEmpty || val.length <= 2) {
                            return "الرجاء ادخال تعليق صحيح";
                          } else {
                            return null;
                          }
                        },
                        style: TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.comment, color: Colors.white),
                          labelText: 'ادخل تعليقك',
                          labelStyle: TextStyle(color: Colors.white),
                          prefixStyle: TextStyle(color: Colors.white),
                          iconColor: Colors.blue,
                          contentPadding: EdgeInsets.symmetric(
                            vertical: 10,
                            horizontal: 20,
                          ),
                          prefixIconColor: Colors.blue,
                          suffixIcon: CommentController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  splashRadius: 22,
                                  onPressed: () => CommentController.clear(),
                                  icon: Icon(Icons.close),
                                ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                          ),
                          focusColor: Colors.blue,
                          hoverColor: Colors.blue,
                        ),
                      ),
                    ),
                    SizedBox(width: 10),
                    TextButton(
                      style: ButtonStyle(),
                      onPressed: () async {
                        if (CommentController.text.isEmpty ||
                            CommentController.text.length < 3) {
                          Fluttertoast.showToast(
                            msg: 'يجب على تعليقك ان يكون حرفين او اكثر',
                            backgroundColor: kBackgroundColor,
                          );
                        } else {
                          final commentid = FirebaseFirestore.instance
                              .collection('Comments')
                              .doc(widget.title)
                              .collection('Comments')
                              .doc();

                          final json = {
                            'id': commentid.id,
                            'sender': signinUser.displayName,
                            'img': signinUser.photoURL,
                            'time': FieldValue.serverTimestamp(),
                            'text': CommentController.text,
                          };

                          await commentid.set(json);

                          CommentController.clear();
                        }
                      },
                      child: Text(
                        'ارسال',
                        style: TextStyle(
                          color: Colors.blue,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          CommentsStreamBuilder(
            title: '${widget.title}',
          ),
        ],
      )),
    );   } }



class CommentsLine extends StatelessWidget {
  CommentsLine(
      {required this.time,
      this.title,
      this.img,
      this.text,
      this.sender,
      required this.isMe});
  final String? title;
  final Timestamp time;
  final String? sender;
  final String? text;
  final bool isMe;

  final String? img;

  @override
  Widget build(BuildContext context) {
    DateTime minAgo = DateTime.now().subtract(const Duration(minutes: 1));
    DateTime secAgo = DateTime.now().subtract(const Duration(seconds: 1));
    DateTime dayAgo = DateTime.now().subtract(const Duration(days: 1));
    DateTime monAgo = DateTime.now().subtract(const Duration(days: 30));
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8), color: kBackgroundColor),
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      '$sender',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                     time != null ?  timeago.format(time.toDate(), locale: 'ar': ""), // here check if time is null or not 
                      style: TextStyle(color: Colors.white70, fontSize: 12),
                    )
                  ],
                ),
                SizedBox(
                  width: 10,
                ),
                CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage('$img'),
                ),
              ],
            ),
            SizedBox(
              height: 8,
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '$text',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CommentsStreamBuilder extends StatelessWidget {
  CommentsStreamBuilder({this.title});
  final String? title;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore
          .collection('Comments')
          .doc('$title')
          .collection('Comments')
          .orderBy('time')
          .snapshots(),
      builder: (context, snapshot) {
        List<CommentsLine> commentsWidget = [];

        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: kBackgroundColor,
            ),
          );
        }
        if (snapshot.data?.docs.isEmpty != false) {
          return Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/cry.gif',
                  height: 110,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  "لاتوجد تعليقات",
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          );
        }
        final messages = snapshot.data!.docs.reversed;
        for (var message in messages) {
          final messagetext = message.get('text');
          final messgaesender = message.get('sender');
          final messgaeimg = message.get('img');
          final datatime = message.get('time');
          final currentUser = signinUser.displayName;

          final commentWidget = CommentsLine(
            sender: messgaesender,
            time: datatime,
            img: messgaeimg,
            text: messagetext,
            isMe: currentUser == messgaesender,
            title: title,
          );
          commentsWidget.add(commentWidget);
        }

        return Expanded(
          child: ListView(
            reverse: false,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
            children: commentsWidget,
          ),
        );
      },
    );
  }
}

所以问题可能是你没有正确清除你的资源。 initState方法中,你有这样的东西:

@override
void initState() {
  getcurrentuser();

  CommentController.addListener(() => setState(() {})); // This causes the issue
 
  super.initState();
}

问题是addListener回调即使在_CommentsState被卸载后也会执行。 意思是,当您添加侦听器时,您也应该稍后将其删除。

你可以这样做:

class _CommentsState extends State<Comments> {
  @override
  void initState() {
    super.initState(); // Notice I moved this up as well
    
    getcurrentuser();

    CommentController.addListener(_updateState); // Add listener on init
  }

  @override
  void dispose() {
    CommentController.removeListener(_updateState); // Remove listener on dispose

    super.dispose();
  }

  void _updateState() => setState(() {});

  @override
  Widget build(BuildContext context) {
    ...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM