how to show directly home screen if data is not null from FlutterSecureStorage?

Viewed 37

I use FutureBuilder for get data from FlutterSecureStorage. And then if the data is not null, Provider set auth state true. So I hope the app to show directly Home Screen. but below code, the app show login page and then home screen. I think below logger.d should show true, because i set true by above code(setUserAuth(true)). but it show false. I cannot understand why it show false.

if (snapshot.data != null) {
  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  Provider.of<AuthenticationNotifier>(context, listen: false).setUserAuth(true)});
  logger.d(Provider.of<AuthenticationNotifier>(context, listen: false).isAuthenticated); 
   // this is call false. I think this should call true. because i set true by above code.
  }

Full code.

Future _getUserId() async {
    final userId = await storage.read(key: "userId");
    return userId;
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      builder: (BuildContext context, Widget? child) {
        return MultiProvider(
            providers: [
              ChangeNotifierProvider<AuthenticationNotifier>.value(
                  value: authNotifier),
            ],
            child: FutureBuilder(
              future: _getUserId(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.data != null) {
                    WidgetsBinding.instance
                        .addPostFrameCallback((timeStamp) {
                      Provider.of<AuthenticationNotifier>(context, listen: false).setUserAuth(true);
                    });
                    logger.d(Provider.of<AuthenticationNotifier>(context, listen: false).isAuthenticated); // this is call false.
                  }
                  FlutterNativeSplash.remove();
                  return MaterialApp.router(
                    routeInformationParser: BeamerParser(),
                    routerDelegate: _routerDelegate,
                  );
                } else {
                  return Container();
                }
              },
            ));
      },
    );
  }
}

BeamerDelegate and Guard.

final _routerDelegate = BeamerDelegate(
  updateListenable: authNotifier,
  guards: [
    BeamGuard(
      beamToNamed: (origin, target) => '/$locationAuth',
      pathPatterns: [
        ...HomeLocation().pathPatterns,
      ],
      check: (context, location) {
        logger.d(Provider.of<AuthenticationNotifier>(context, listen: false).isAuthenticated);
        return Provider.of<AuthenticationNotifier>(context, listen: false)
            .isAuthenticated;
      },
    ),
  ],
  locationBuilder: BeamerLocationBuilder(beamLocations: [
    HomeLocation(),
    AuthLocation(),
  ]),
);
0 Answers
Related