Usama Fayyaz
Usama Fayyaz

Reputation: 51

Flutter : This widget has been unmounted, so the State no longer has a context (and should be considered defunct) Error when using streambuilder

    class _MyAppState extends State<MyApp> {
  bool isFirstTime = true;
  bool? isRegistered;
  checkIfRegisteredOrNot() async {
    print("Checking if registered");
    if (isFirstTime && mounted) {
      print("Insided mounted");
      final id = FirebaseAuth.instance.currentUser!.uid;
      DocumentSnapshot ds =
          await FirebaseFirestore.instance.collection("users").doc(id).get();
      setState(() {
        print("Setting state");
        isRegistered = ds.exists;
        isFirstTime = false;
        print("isRegistered: $isRegistered");
        print("isFirstTime: $isFirstTime");
      });
    }
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SehatMand',
      theme: ThemeData(
          scaffoldBackgroundColor: Color(0xFF222831),
          inputDecorationTheme: InputDecorationTheme(
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(2),
                borderSide: BorderSide(color: Colors.deepPurpleAccent)),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(2),
              borderSide: BorderSide(color: Colors.deepPurpleAccent, width: 5),
            ),
          ),
          colorScheme: ColorScheme.dark().copyWith(
            secondary: Colors.deepPurpleAccent,
          )),
      home: StreamBuilder(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            print("Has data");
            checkIfRegisteredOrNot();
            if (isRegistered != null) {
              return isRegistered! ? const TestScreen() : const FormScreen();
            } else {
              print("isRegistered is null");
              return const Scaffold(
                  body: Center(child: CircularProgressIndicator()));
            }
          } else {
            print('LoginScreen');
            return const LoginScreen();
          }
        },
      ),
      routes: {
        MainScreen.routeName: (context) => MainScreen(),
        FormScreen.routeName: (context) => const FormScreen(),
      },
    );
  }
}

Description of the error i am getting

======== Exception caught by scheduler library ===================================================== The following assertion was thrown during a scheduler callback: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).

**> Consider canceling any active work during "dispose" or using the

"mounted" getter to determine if the State is still active. When the exception was thrown, this was the stack: #0 State.context. (package:flutter/src/widgets/framework.dart:942:9) #1 State.context (package:flutter/src/widgets/framework.dart:948:6) #2 _TransformerPageViewState._onGetSize (package:another_transformer_page_view/src/another_transformer_page_view.dart:450:24) #3 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15) #4 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1089:9) #5 SchedulerBinding.scheduleWarmUpFrame. (package:flutter/src/scheduler/binding.dart:862:7) (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch) ** ====================================================================================================

Upvotes: 1

Views: 4383

Answers (1)

Piyush Kumar
Piyush Kumar

Reputation: 482

Do a if (mounted) check before calling setState.

Upvotes: 3

Related Questions