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



我正在尝试实现用户登录会话。我愿意跳过登录屏幕并愿意导航到主屏幕。我创建了两个屏幕并实现了共享首选项来存储用户响应。我能够保存并打印回来。我在 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;
}

我正在使用三元条件来检查和加载正确的屏幕。 但它是上面代码中的函数(检查用户和导航(上下文((== 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;
}

checkUserAndNavigate返回一个未来,这就是你收到错误的原因。您可以使用空白的加载屏幕/初始屏幕来读取首选项并从那里导航到正确的屏幕:

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

使用FutureBuilder更容易。此小部件基于未来的结果构建自身。

考虑一下:

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 { ... }

无需操作导航器堆栈。

最新更新