I'm trying to implement the user authentification into my Flutter app that is supposed to work for both Android and iOS.
I am using the JWT for the authentification of the app's request to the server, so I provide the user with a JWT token at login and the app saves the token securely on the device and then uses the token to communicate with my server.
When the app launches, I run the HomePage where there is a if statement where app looks to the secure storage for a JWT token if there is no token, the app shows the login page.
HomePage class:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.orange,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'App Title'),
routes: <String, WidgetBuilder>{
'/login': (BuildContext context) => new SignInPage(),
},
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
...
@override
Widget build(BuildContext context) {
storage.read(key: 'jwt_token').then((token) {
logger.d('MAIN APP GOT TOKEN: ' + token.toString());
if (token == null) {
Navigator.pushReplacementNamed(context, '/login');
}
});
return Scaffold(...);
}
}
I tried Navigator.pushReplacementNamed
, Navigator.pushNamed
, Navigator.popAndPushNamed
... All of those get me to the login page. So that's fine. My problem is, that it doesn't work the other way around.
When I login sucessfully (obtain a JWT token), I can't make the app to return to the home page. If I restart the application it correctly shows the home page (as now there is a JWT in the secure storage), so the token check works fine. It must be something in rerouting from the login page to the home page.
login page snippet:
if (serverResponse.containsKey('jwt_token')) {
await storage.write(
key: 'jwt_token', value: serverResponse['jwt_token']);
Navigator.pushReplacementNamed(context, '/');
I tried also Navigator.pop
and Navigator.pushNamed(context, '/')
, Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false)
, Navigator.pushReplacementNamed(context, '/')
, non of which worked.
It looks like the page is changing, but it ends up being the login page again. I checked that the token is already inside the storage when the rerouting command is called. Also I have a debug message above the token check in the HomePage and the debug string is never printed after the login, so the Home page is simply not called at all.
Do you see something wrong in my code? How can I make it work?