I'm trying to do autologin function for my flutter web app using provider. I couldn't find any articles or videos about this and I wonder how it should implemented. What I'm trying to do is check the shared preferences before launching site. App uses URL routing so I have to do the checking whatever url the user goes. Here is my main code.
void main() {
setUrlStrategy(PathUrlStrategy());
setupLocator();
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => AppStateProvider())],
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
final RouteInformationProvider? routeInformationProvider;
const MyApp({Key? key, this.routeInformationProvider}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Title',
theme: ThemeData(
primarySwatch: Colors.grey,
fontFamily: 'Poppins'
),
// home: HomeView(),
routerDelegate: RoutemasterDelegate(
routesBuilder: (context) {
return buildRouteMap(context);
},
),
routeInformationParser: RoutemasterParser(),
routeInformationProvider: routeInformationProvider,
);
}
}
And here is my AppStateProvider class
class AppStateProvider extends ChangeNotifier {
bool loading = false;
AppStateModel? appState;
checkCaches() async {
loading = true;
final prefs = await SharedPreferences.getInstance();
final String? acToken = prefs.getString('accessToken');
if (acToken != null) {
appState?.isLoggedIn = true;
appState?.accessToken = acToken;
final String? comToken = prefs.getString('companyToken');
appState?.companyToken = comToken;
loading = false;
notifyListeners();
} else {
appState?.isLoggedIn = false;
notifyListeners();
}
}
storeCaches(String acToken, String? comToken) async {
loading = true;
final prefs = await SharedPreferences.getInstance();
prefs.setString('accessToken', acToken);
prefs.setString('companyToken', comToken!);
appState?.isLoggedIn = true;
appState?.accessToken = acToken;
appState?.companyToken = comToken;
loading = false;
notifyListeners();
}
}
Any ideas about the implementation?