Home > Software design >  Error While Navigating From Splash Screen to the next screen in Flutter
Error While Navigating From Splash Screen to the next screen in Flutter

Time:10-13

I made stateless widget splash screen that test if the user is already logged in then will open mainhome screen immediately except that it will open sign in screen. It is working well but there is errors...

output:

E/flutter (21294): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (21294): At this point the state of the widget's element tree is no longer stable.
E/flutter (21294): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter (21294): #0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:4241:9)
E/flutter (21294): #1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:4255:6)
E/flutter (21294): #2      Element.findAncestorStateOfType (package:flutter/src/widgets/framework.dart:4322:12)
E/flutter (21294): #3      Navigator.of (package:flutter/src/widgets/navigator.dart:2549:40)
E/flutter (21294): #4      SplashScreen.build.<anonymous closure> (package:fbissalama/Screens/splashscreen.dart:20:18)
E/flutter (21294): #5      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (21294): #6      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (21294): #7      _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (21294): #8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<Following>(
          create: (BuildContext context) => Following(),
        ),
        ChangeNotifierProvider<ProviderController>(
          create: (BuildContext context) => ProviderController(),
        ),
        ChangeNotifierProvider<Verifying>(
          create: (BuildContext context) => Verifying(),
        ),
        //TODO
        //Add AuthController Here...
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "Bissalama",
        onGenerateRoute: onGenerate,
        initialRoute: AppRoutes.splashScreenPage,
        routes: {
          AppRoutes.loginPage: (context) => const SignInScreen(),
          AppRoutes.splashScreenPage: (context) => const SplashScreen(),
          AppRoutes.mainHomePage: (context) => const MainHome(),
          AppRoutes.addJourneyPage: (context) => const AddJourneyPage(),
          AppRoutes.currentJourneyPage: (context) => const CurrentJourneyPage(),
          AppRoutes.favoriteJourneyPage: (context) => const FavoritePage(),
          AppRoutes.settingsPage: (context) => const SettingsPage(),
          AppRoutes.aboutPage: (context) => const AboutPage(),
        },
      ),
    ),
  );
}

splashscreen.dart:

class SplashScreen extends StatelessWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Timer(const Duration(seconds: 1), () {
      final String? user = FirebaseAuth.instance.currentUser?.phoneNumber;
     final String? user1 = FirebaseAuth.instance.currentUser?.email;
     if (user1 != null || user != null) {
       Navigator.of(context).pushReplacementNamed('/home');
     } else {
       Navigator.of(context).pushReplacementNamed('/');
     }
    });
    return Scaffold(
      body: Container(
        color: Colors.blueAccent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Center(
                child: Image.asset(
                  AppAssets.busIcon,
                  fit: BoxFit.fitHeight,
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              Text(
                "Bissalama",
                style: GoogleFonts.lobster(
                  textStyle: const TextStyle(
                      color: Colors.white,
                      fontSize: 30,
                      fontWeight: FontWeight.bold),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              const SpinKitPouringHourGlassRefined(
                  color: Colors.white, size: 50.0),
            ],
          ),
      ),
    );
  }
}

I searched A lot about this problem I may recognize the problem, maybe I'm using a context which is disposed like I'm navigating with a disposed context, I didn't see any Solution. How Can I solve this Error in Stateless widget.

CodePudding user response:

class SplashScreen extends StatelessWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: Future.delayed(const Duration(seconds: 1), () async {
          final String? user = FirebaseAuth.instance.currentUser?.phoneNumber;
          final String? user1 = FirebaseAuth.instance.currentUser?.email;
          if (user1 != null || user != null) {
            Navigator.of(context).pushReplacementNamed('/home');
          } else {
            Navigator.of(context).pushReplacementNamed('/');
          }
        }),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          return Container(
            color: Colors.blueAccent,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Center(
                  child: Image.asset(
                    AppAssets.busIcon,
                    fit: BoxFit.fitHeight,
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                Text(
                  "Bissalama",
                  style: GoogleFonts.lobster(
                    textStyle: const TextStyle(color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                const SpinKitPouringHourGlassRefined(color: Colors.white, size: 50.0),
              ],
            ),
          );
        },
      ),
    );
  }
}

Try this

  • Related