Home > Net >  Not updating the value of bool variable
Not updating the value of bool variable

Time:06-12

Here you have the code from MyApp:

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  bool isLoggedIn = false;



  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    comprobarEstado();
  }
  Future<void> comprobarEstado() async {

    final SharedPreferences prefs = await SharedPreferences.getInstance();
     isLoggedIn = ((prefs.getBool('logeado') == null) ? false : prefs.getBool('logeado'))!;
     print ("Estado ${isLoggedIn}");

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        localizationsDelegates: context.localizationDelegates,
        supportedLocales: context.supportedLocales,
        locale: context.locale,
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home:  isLoggedIn ? MyHomePage() : LoginScreen());
  }
}

If the value of isLoggedIn is true, I want to launch MyHomePage, and if it is false I want to launch LoginPage.

The current value for isLoggedIn is true, but it always launch LoginPage.

I would like to know the proper way to get the value for isLoggedIn and to open the right page depending on its value.

CodePudding user response:

The comprobarEstado method is async and your widget will be built before the future is resolved and you have no code to trigger a rebuild once the value changes. An easy fix is to change your method to:

Future<void> comprobarEstado() async {

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
     isLoggedIn = ((prefs.getBool('logeado') == null) ? false : prefs.getBool('logeado'))!;
    });
     
     print ("Estado ${isLoggedIn}");

  }

Calling setState is going to trigger the widget to rebuild.

  • Related