In any production app, the user is directed to a route based on some authentication logic whenever the app is opened. For example, in your Flutter App, you have at least two routes, Login and Dashboard. The problem is how can you decide which route should a user be redirected to?
In this tutorial, you’ll check the value of a locally stored boolean variable to dynamically decide the home route. You can use any method for writing your authentication logic, like checking the validity of the API token, but for the sake of simplicity, you’ll explore a simple logic.
Contents
Prerequisites
Before proceeding, make sure to set up a Flutter app with at least two different screens.
Installing Dependencies
For this tutorial, add the following dependencies in your pubspec.yaml:
dependencies:
shared_preferences: ^0.5.12+4
async: ^2.4.2
Make sure to add the latest version of the dependencies from pub.dev.
After adding these dependencies, it is now time to install them. In your terminal, execute the following command:
flutter pub get
Shared Preferences is a Flutter plugin for reading and writing key-value pairs to the local storage. Async contains the utility functions and classes related to the dart:async library.
Writing Code
In the lib/main.dart, add the following code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
// handle exceptions caused by making main async
WidgetsFlutterBinding.ensureInitialized();
// init a shared preferences variable
SharedPreferences prefs = await SharedPreferences.getInstance();
// get the locally stored boolean variable
bool isLoggedIn = prefs.getBoolean('is_logged_in');
// define the initial route based on whether the user is logged in or not
String initialRoute = isLoggedIn ? '/' : 'login';
// create a flutter material app as usual
Widget app = MaterialApp(
...
initialRoute: initialRoute,
);
// mount and run the flutter app
runApp(app);
}
In the above code, you are getting the value of the is_logged_in
boolean variable, and based on it decide the value of the initialRoute
and pass it to the MaterialApp
widget.
One important thing in the above code is the use of the async-await pattern. You can also use then
but it makes the code a little messy and that’s what you should try to avoid here. Making your main()
function asynchronous can cause some exceptions, so to solve this, you need to add WidgetsFlutterBinding.ensureInitialized()
.
Results
That’s it. You have successfully written a code that allows you to redirect the user to the Dashboard page if they are logged in, otherwise to the Login page.