首页 文章

如何确定main.dart文件中的默认导航以及如何根据条件检查更改它?

提问于
浏览
1

我正在尝试实现用户登录会话 . 我愿意跳过登录屏幕并愿意导航到主屏幕 . 我创建了两个屏幕并实现了共享首选项来存储用户响应 . 我可以保存并打印回来 . 我在if条件中遇到问题,我试图检查从用户检查函数返回的布尔值,该函数检查已保存的共享首选项值并基于此返回true或false .

{
       return new MaterialApp(
          home: new Scaffold(
            body: ((checkUserAndNavigate(context))== true)
                ? new HomeScreen()
                : new LoginScreen(),
          ),
    }


    //Check if user login is saved
    Future checkUserAndNavigate(BuildContext context) async 
    {
      bool status;
      print("Checking user state");
      SharedPreferences preferences = await SharedPreferences.getInstance();
      String userdata = preferences.getString("userData");
      if (userdata != null) {
        status = true;
      } else {
        status = false;
      }
      return status;
    }

我正在使用三元条件来检查和加载适当的屏幕 . 但它的上述代码中的函数(checkUserAndNavigate(context))== true)总是说下面的错误 "Equality operator '==' invocation with reference of unrelated types"

完整的代码如下

import 'dart:async';

    import 'package:flutter/material.dart';

    import './app/src/screens/loginscreen.dart';
    import './app/src/screens/homescreen.dart';
    import 'package:shared_preferences/shared_preferences.dart';

    void main() => runApp(new MTrackNotificationsMain());

    class MTrackNotificationsMain extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        // This widget is the root of your application
        return new MaterialApp(
          home: new Scaffold(
            body: (checkUserAndNavigate(context) == true)
                ? new HomeScreen()
                : new LoginScreen(),
          ),
          theme: new ThemeData(
            primaryColor: Colors.teal.shade400,
            primaryColorDark: Colors.teal.shade800,
            primarySwatch: Colors.teal,
            accentColor: Colors.teal.shade300,
          ),
          //Routes attribute work as screen navigator
          routes: {
            "/LoginScreen": (BuildContext context) => new LoginScreen(),
            '/HomeScreen': (BuildContext context) => new HomeScreen()
          },
        );
      }
    }

    //Check if user login is saved
    Future checkUserAndNavigate(BuildContext context) async {
      bool status;
      print("Checking user state");
      SharedPreferences preferences = await SharedPreferences.getInstance();
      String userdata = preferences.getString("userData");
      if (userdata != null) {
        status = true;
      } else {
        status = false;
      }
      return status;
    }

2 回答

  • 1

    使用FutureBuilder更容易 . 这个Widget根据Future的结果构建自己 .

    考虑一下:

    void main() => MyApp();
    
    class MyApp extends StatelessWidget {
       Future<bool> isLoggedIn() async {
         SharedPreferences prefs = await SharedPreferences.getInstance();
         return prefs.getBool("loggedIn");
       }
    
       @override
       Widget build(BuildContext context) {
         return MaterialApp(
           home: FutureBuilder(
             future: isLoggedIn(),
             builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
               if (snapshot.hasData) {
                 return snapshot.data ? Main() : Login();
               }
               return Container(); // noop, this builder is called again when the future completes
             },
           );
         );
       }
    }
    
    class Main extends StatelessWidget { ... }
    class Login extends StatelessWidget { ... }
    

    无需操纵Navigator堆栈 .

  • 0

    checkUserAndNavigate 正在返回一个Future,这就是你得到这个错误的原因 . 您可以使用空白加载屏幕/启动画面来读取首选项并从那里导航到正确的屏幕:

    import 'package:flutter/material.dart';
    import 'dart:async';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new SplashScreen(),
          routes: {
            '/main': (context) => MyHomePage(title:'Home Page'),
            '/other': (context) => MyHomePage(title:'Other Page'),
          }
        );
      }
    }
    
    Future<bool> checkUserAndNavigate(BuildContext context) async {
      return false;
    } 
    
    class SplashScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        checkUserAndNavigate(context).then((res) {
          if (res == true) {
            Navigator.pushNamed(context, '/main');
          } else {
            Navigator.pushNamed(context, '/other');
          }
        });
    
        return new Scaffold(
          body: new Card(
            child: new Center(
              child:
                new Text('Loading.....',
                  style: new TextStyle(fontSize: 24.00,
                     fontWeight: FontWeight.bold,
                     color: Colors.indigo)
                ),
              )
            ),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text(widget.title),
          ),
        body: new Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text(
                'You have pushed the button this many times:',
              ),
              new Text(
                '$_counter',
                style: Theme.of(context).textTheme.display1,
              ),
            ],
          ),
        ),
        floatingActionButton: new FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: new Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      );
    }
     }
    
     class OtherPage extends StatefulWidget {
       OtherPage({Key key, this.title}) : super(key: key);
    
       final String title;
    
       @override
       _OtherPageState createState() => new _OtherPageState();
     }
    
     class _OtherPageState extends State<OtherPage> {
       int _counter = 0;
    
       void _incrementCounter() {
         setState(() {
           _counter++;
         });
       }
    
       @override
       Widget build(BuildContext context) {
         return new Scaffold(
           appBar: new AppBar(
              title: new Text(widget.title),
           ),
           body: new Center(
             child: new Column(
               mainAxisAlignment: MainAxisAlignment.center,
               children: <Widget>[
                  new Text(
                    'You have pushed the button this many times:',
                  ),
                  new Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.display1,
                  ),
               ],
             ),
           ),
        floatingActionButton: new FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: new Icon(Icons.add),
         ), // This trailing comma makes auto-formatting nicer for build methods.
      );
    }
    }
    

    更改 checkUserAndNavigate 的返回值,您将看到如何加载不同的屏幕 .

相关问题