How To Set Default Page Conditionally In Flutter


In this article, we will learn how to set a default page conditionally in Flutter. This is a very important concept for app development. We will use sharedPreferences to make the condition for the page on which we will want to navigate. If you are new to Flutter and don’t know about shared preferences, then check out my another article SharedPreferences In Flutter. So, let’s start with the scenario.


So now, let's take an example. Suppose you have an app in which you need authentication from the user, for, let’s say, Google or Facebook authentication. After authentication, you navigate to the home page. When the user first time authenticates and goes to the home page, it’s all working well but when the user closes the app and starts the app again, he/she needs to authenticate himself/herself again which is not a good idea. In this case, we need to bypass the authentication process and directly redirect this user to the home page. So, we need conditional navigation.


Below is the program for conditional navigation.
_decideMainPage() will conditionally navigate to home or registration page.
  1. import 'package:flutter/material.dart';  
  2. import 'package:flutter_chat_app/pages/home_page.dart';  
  3. import 'package:flutter_chat_app/pages/registration_page.dart';  
  4. import 'package:shared_preferences/shared_preferences.dart';  
  6. void main() {  
  7.   SharedPreferences.getInstance().then((prefs) {  
  8.     runApp(LandingPage(prefs: prefs));  
  9.   });  
  10. }  
  12. class LandingPage extends StatelessWidget {  
  13.   final SharedPreferences prefs;  
  14.   LandingPage({this.prefs});  
  15.   @override  
  16.   Widget build(BuildContext context) {  
  17.     return MaterialApp(  
  18.       theme: ThemeData(  
  19.         primarySwatch:,  
  20.       ),  
  21.       home: _decideMainPage(),  
  22.     );  
  23.   }  
  25.   _decideMainPage() {  
  26.     if (prefs.getBool('is_verified') != null) {  
  27.       if (prefs.getBool('is_verified')) {  
  28.         return HomePage(prefs: prefs);  
  29.         // return RegistrationPage(prefs: prefs);  
  30.       } else {  
  31.         return RegistrationPage(prefs: prefs);  
  32.       }  
  33.     } else {  
  34.       return RegistrationPage(prefs: prefs);  
  35.     }  
  36.   }  
  37. }  


In this article, we have learned how to conditionally navigate to default page in Flutter.