Search code examples
flutterflutter-provider

Is there a way to trigger the page navigation when a specific variable in provider class changes?


is there a way to trigger the page navigation when a specific variable in provider class changes? for example. I want to navigate to login screen whenever the appLock variable becomes true otherwise do nothing

 void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  runApp(MultiProvider(providers: [
    ChangeNotifierProvider(create: (_) => AppLockHelper()),
  ], child: const MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    context.read<AppLockHelper>().startThread();
  }

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: kWhiteColor,
      ),
      supportedLocales: L10n.all,
      initialRoute: '/',
      onGenerateRoute: RouteGenerator.generateRoute,
    );
  }
}

and this is my provider class

 class AppLockHelper extends ChangeNotifier {
  bool _appLocked = false;
  bool get appLocked => _appLocked;
  final _get = GenericGetApi();
  Timer? timer;
  void startThread() {
    timer = Timer.periodic(
        const Duration(seconds: 15), (Timer t) => getAppStatus());
  }

  void stopThread() {
    timer?.cancel();
  }

  Future<void> getAppStatus() async {
    var appStatusResult =
        await _get.get(endpoint: EndPointsPool.getAppLockStatus);
    appStatusResult.fold((l) {
      _appLocked = false;
    }, (r) {
      AppLock appLockResult = AppLock.fromJson(r);
      _appLocked = appLockResult.applocked;
    });
    notifyListeners();
  }
}

Solution

  • Okay the solution would be add a listner in initState.

     @override
      void initState() {
        super.initState();
        final myNotifier = context.read<AppLockHelper>();
        void listener() {
          myNotifier.appLocked
              ? Navigator.pushNamedAndRemoveUntil(context, "/log-in", (_) => false)
              : null;
        }
    
        myNotifier.addListener(listener);
      }