简体   繁体   中英

How Add a If statement to main.dart file

I want to add an if statement function where if current user.= null it should nav to Home() and not then it should nav to Login().

this is the current main file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MaterialApp(
    title: 'TaakStore',
    home: StreamBuilder(
    stream: FirebaseAuth.instance.authStateChanges(),
    builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
      if (snapshot.hasData) {
        print(snapshot);
        return Home();
      } else {
        return Login();
      }
    },
  ),
  ));
}

instead of the streambuilder i want to add a firebase auth function

this

if(FirebaseAuth.instance.currentUser != null){
  Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home();));
}
else{
  Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Login();));
}

Please help me!!

You can use ternary operation like so:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  bool loggedIn = FirebaseAuth.instance.currentUser !=null;
  runApp(MaterialApp(
    title: 'TaakStore',
    home: loggedIn ? Home(): Login(),
  ),
 );
}

I recommend you to use 'routes' in MaterialApp, I can give you an example here:

initialRoute: await AppRoute.getInitialRoute()

and open AppRoute and define there

static Future<String> getInitialRoute() {

    if (FirebaseAuth.instance.currentUser != null) {
      return '/home-page';
    } else {
      return '/login-page';
    }   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM