flutter - 颤振:'未来' 不是 bool 类型的子类型
问题描述
我试图实现一个简单的登录/注销功能。我的情况是这样的:
我有 2 个页面(登录页面和主页),在其中main.dart
,我使用 SharedPreferences 检查用户是否已经登录,如果用户已登录,我在单击按钮时将布尔值设置为 true。
我遇到的问题是,我创建了一个 routeLogin 函数,用于在 Homepage 和 Landingpage 之间进行选择。我得到这个错误:
I/flutter ( 9026): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9026): The following assertion was thrown building MyApp(dirty):
I/flutter ( 9026): type 'Future<dynamic>' is not a subtype of type 'bool'
I/flutter ( 9026):
I/flutter ( 9026): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 9026): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 9026): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 9026): https://github.com/flutter/flutter/issues/new?template=BUG.md
这是我的代码:
import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
bool checkValue;
checkLoginValue () async{
SharedPreferences loginCheck = await SharedPreferences.getInstance();
checkValue = loginCheck.getBool("login");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: routeLogin());
//home: LandingPage());
}
routeLogin()
{
print("Check value");
if (checkValue == null){
return LandingPage();
}
else{
return HomePage();
}
}
}
请让我知道我哪里出错了,我是 Flutter 的新手。
解决方案
您可以使用未来的构建器轻松获得此行为。
Future<bool> checkLoginValue() async {
SharedPreferences loginCheck = await SharedPreferences.getInstance();
return loginCheck.getBool("login");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FutureBuilder<bool>(
future: checkLoginValue,
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.data == false) {
return LandingPage();
} else {
return HomePage();
}
},
),
);
}
推荐阅读
- javascript - 无法读取未定义 Puppeteer 的属性“长度”
- ruby-on-rails - 如果用户从支付提供商返回后浏览器会话 cookie 丢失,如何从数据库重新加载 ruby on rails 中的会话
- r - 在 dplyr group_by 中过滤,以便保留符合某些条件的行组合
- python - 函数在 django 中的日期范围之间给出错误的工作日总数
- javascript - 如何快速改变播放音调的频率而不会噼啪作响?
- php - DomPdf 渲染黑白图像
- python - 如何将标记器输出转换为训练器 API 在 Huggingface Transformers 中所需的 train_dataset?
- flutter - 当我关闭我的应用程序时,我的数据库正在重置
- javascript - 动态地将类添加到 React map 函数中的前 n 个元素
- mysql - 我需要通过以下方式加入这两个表..使用mysql