Flutter:'Future <dynamic>' 不是 bool 类型的子类型

Flutter : 'Future <dynamic>' is not a subtype of type bool

我试图实现一个简单的 login/logout 功能。我的场景是这样的:

我有 2 个页面(登录页面和主页),在 main.dart 中,我使用 SharedPreferences 检查用户是否已经登录,如果用户已登录,我设置了单击按钮时布尔值为真。

我遇到的问题是,我创建了一个 routeLogin 函数来在主页和登陆页之间进行选择。 我得到这个错误:

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 的新手。

checkValue 的值为 Future 而不是 bool

Future checkValue;

因此您可以检查它是否返回了值或错误。

routeLogin() {
  print("Check value");
  checkValue.then((res) {
    return LandingPage();
  }).catchError(
    (e) {
      return HomePage();
    },
  );
}

假设您的 getBool 函数来自 loginCheck returns 未来,

您正在尝试将 Future 放入布尔值中。

将该行更改为:

checkValue = await loginCheck.getBool("login");

您可以使用 future builder 轻松获得此行为。

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();
        }
      },
    ),
  );
}

异步函数必须return一个 Future<>。这是您如何执行此操作的示例。

首先创建您的 getLoginStatus() 函数

Future<bool> getLoginStatus() async {
  try {
    var isLogin = SharedPref.pref.getBool('isLogin');
    return isLogin != null ? true : false;
  } catch (e) {
    print(e);
    return false;
  }
}

像这样调用该函数后

routeLogin() {
  getLoginStatus().then((isLogin) {
    print("isLogin == $isLogin");
    if (isLogin) {
      navigateToNextScreen(HomePage());
    } else {
      navigateToNextScreen(LoginPage());
    }
  });
}