如何确定main.dart文件中的默认导航,以及如何基于条件检查进行更改?

时间:2018-07-03 06:02:30

标签: dart flutter

我正在尝试实现用户登录会话。我愿意跳过登录屏幕,并愿意导航到主屏幕。我创建了两个屏幕,并实现了共享首选项来存储用户响应。我可以保存并打印回来。我在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)总是在说如下错误 “引用不相关类型的平等运算符'=='”

完整代码如下



    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 个答案:

答案 0 :(得分:1)

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的返回值,您将看到如何加载其他屏幕。

答案 1 :(得分:0)

使用FutureBuilder更容易。此小部件会根据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 { ... }

无需操纵导航器堆栈。