Home > Enterprise >  Flutter initState not working when pushing navigator
Flutter initState not working when pushing navigator

Time:11-25

This is the code where the initState is not working

class _MyAppState extends State<MyApp> {
  late bool _nightMode;

  Future<void> _loadNightMode() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _nightMode = (prefs.getBool('nightMode') ?? false);
    });
  }

  @override
  void initState() {
    super.initState();
    _loadNightMode();
    print("HELLO");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: _nightMode ? ThemeMode.dark : ThemeMode.light,
      debugShowCheckedModeBanner: false,
      home: const LandingPage(),
    );
  }
}

I tried printing HELLO as a testing but it resulted in nothing actually.

This is how I call it.


  logout() {
    FirebaseAuth.instance.signOut();
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (BuildContext context) {
          return const MyApp();
        },
      ),
    );
  }

As you can see, I am trying to pass the sharedpreferences to get a bool but with the initState not working it's actually not getting passed. There is also no error popping out.

CodePudding user response:

Navigator use context and when initstate called context not ready yet so don't use navigator or any context related work in initstate

CodePudding user response:

Try to add _loadNightMode() method call in callback inside initState method because of context not available yet:

WidgetsBinding.instance.addPostFrameCallback((_) async {
  _loadNightMode();
});

Second options is move _loadNightMode() into didChangeDependencies() widget lifecycle callback function.

  • Related