Exception has occurred. FlutterError (setState() called after dispose(): _MyProfileState#c3ad1(lifecycle state: defunct, not mounted)

Viewed 2976

This Error Showing When i Click On Notification Navigation Item from Profile Page To Notification

Exception has occurred. FlutterError (setState() called after dispose(): _MyProfileState#c3ad1(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().)

Profile Page :

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:play_big_win/constants.dart';
import 'package:play_big_win/services/firebase-auth-helper.dart';

class MyProfile extends StatefulWidget {
  @override
  _MyProfileState createState() => _MyProfileState();
}

class _MyProfileState extends State<MyProfile> {
  final firebaseUser = FirebaseAuth.instance.currentUser;
  final db = FirebaseFirestore.instance;
  String fullname = '';
  String email = '';
  @override
  void dispose() {
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
    super.dispose();
  }

  @override
  initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  getData() async {
    while (mounted) {
      dynamic names = await FirebaseAuthHelper().getCurrentUserData();
      if (names != null) {
        fullname = names[0];
        email = names[1];
        setState(() {});
      } else {
        print("Nulllll");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold(
      backgroundColor: kPrimaryColor,
      body: SafeArea(
        child: ListView(
          shrinkWrap: true,
          children: [
            SizedBox(
              height: 20,
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(
                      Radius.circular(15),
                    ),
                  ),
                  width: MediaQuery.of(context).size.width - 25,
                  height: 150,
                  child: Row(
                    children: [
                      CircleAvatar(
                        radius: 60.0,
                        backgroundImage: NetworkImage(
                          'https://res.cloudinary.com/dqunmzmqo/image/upload/v1606248032/male-clipart-avatar_ewaerc.png',
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 45.0),
                        child: Column(
                          children: [
                            Text(
                              "Name: $fullname",
                              style: TextStyle(
                                fontSize: 14,
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Email: $email",
                              style: TextStyle(
                                fontSize: 14,
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Refer Code: Xasdsas",
                              style: TextStyle(
                                fontSize: 14,
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    'Play Big Win Big',
                    style: TextStyle(
                      fontFamily: 'Pacifico',
                      fontSize: 20.0,
                      color: Colors.white,
                    ),
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  'V1.0',
                  style: TextStyle(
                    fontSize: 10.0,
                    letterSpacing: 2.5,
                    color: Colors.teal.shade100,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  height: 20.0,
                  width: 150.0,
                  child: Divider(
                    color: Colors.teal.shade100,
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // Navigator.push(

                    //     context,

                    //     MaterialPageRoute(

                    //       builder: (context) => MyprivacyPolicy(),

                    //     ));
                  },
                  child: Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.group_add,
                        color: Colors.teal,
                      ),
                      title: Text(
                        'Invite Friends',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0,
                          color: Colors.teal.shade900,
                        ),
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // Navigator.push(

                    //     context,

                    //     MaterialPageRoute(

                    //       builder: (context) => MyprivacyPolicy(),

                    //     ));
                  },
                  child: Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.question_answer,
                        color: Colors.teal,
                      ),
                      title: Text(
                        "FAQ's",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0,
                          color: Colors.teal.shade900,
                        ),
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // Navigator.push(

                    //     context,

                    //     MaterialPageRoute(

                    //       builder: (context) => MyprivacyPolicy(),

                    //     ));
                  },
                  child: Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.privacy_tip,
                        color: Colors.teal,
                      ),
                      title: Text(
                        'Privacy Policy',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0,
                          color: Colors.teal.shade900,
                        ),
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // Navigator.push(

                    //     context,

                    //     MaterialPageRoute(

                    //       builder: (context) => TermsandCondtions(),

                    //     ));
                  },
                  child: Card(
                    color: Colors.white,
                    margin:
                        EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
                    child: ListTile(
                      leading: Icon(
                        Icons.auto_fix_normal,
                        color: Colors.teal,
                      ),
                      title: Text(
                        'Terms & Conditions',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 17.0,
                          color: Colors.teal.shade900,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Notification Page:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../constants.dart';

class MyNotification extends StatefulWidget {
  @override
  _MyNotificationState createState() => _MyNotificationState();
}

class _MyNotificationState extends State<MyNotification> {
  @override
  void dispose() {
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
    super.dispose();
  }

  @override
  initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: kPrimaryColor,
        title: Text(
          "Notifications",
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.deepPurple,
              borderRadius: BorderRadius.all(
                Radius.circular(
                  20,
                ),
              ),
            ),
            height: 300,
            width: MediaQuery.of(context).size.width,
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: Text(
                  "Today Is Your sadsadasdas das das dsa sa dsa dsad asd as das asd sad asd asds das sa dsa",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

My Authenticate Code:

Future getCurrentUserData() async {
    try {
      DocumentSnapshot ds = await users.doc(firebaseUser.uid).get();
      String fullname = ds.get('full_name');
      String email = ds.get('email');
      return [fullname, email];
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

This Code Which I Call in Profile Page:

 getData() async {
    while (mounted) {
      dynamic names = await FirebaseAuthHelper().getCurrentUserData();
      if (names != null) {
        fullname = names[0];
        email = names[1];
        setState(() {});
      } else {
        print("Null");
      }
    }
  }
1 Answers

You are using setState in async function, After an await, your widget may not be mounted anymore. Doing setState gives you an exception at that time. use the below code or place it at any other place

if (this.mounted) {
setState(() {
 });
 }

or more clear approach override setState

@override
  void setState(fn) {
    if(mounted) {
      super.setState(fn);
    }
  }
Related