【问题标题】:Flutter : 'Future <dynamic>' is not a subtype of type boolFlutter:'Future <dynamic>' 不是 bool 类型的子类型
【发布时间】:2019-12-05 12:40:33
【问题描述】:

我试图实现一个简单的登录/注销功能。我的情况是这样的:

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

【问题讨论】:

  • 在路由登录函数中 checkvalue 可能等于 null 对我来说没有多大意义。如果共享首选项包含值,为什么不让 getbool 函数返回 true,否则返回 false?

标签: flutter dart future flutter-futurebuilder


【解决方案1】:

checkValue 的值是 Future 而不是 bool

Future checkValue;

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

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

【讨论】:

    【解决方案2】:

    您可以使用 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();
            }
          },
        ),
      );
    }
    

    【讨论】:

    • 这确实帮助了我,但是我有点困惑,当我执行 print(checkLoginValue ()) 时,它给了我一个 'Future' 的实例,我期待一些像 nulll 这样的值。知道如何获得价值吗?
    • 您的方法返回一个未来,因此您必须等待该值。
    • 谢谢你,如果你能帮助理解我需要在代码中的哪个位置放置 await,那将帮助我更好地理解。
    • 我猜在 checkLoginValue() 之前返回 print(loginCheck.getBool("login"))
    • 有一个类型:在FutureBuilder里面应该是“future:checkLoginValue()”;你错过了括号。
    【解决方案3】:

    异步函数必须返回 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());
        }
      });
    }
    

    【讨论】:

      【解决方案4】:

      假设 loginCheck 中的 getBool 函数返回 Future,

      您正在尝试将 Future 放入 bool。

      将该行更改为:

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

      【讨论】:

      • 我已经等了 6 个小时了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2020-01-01
      • 2020-12-09
      • 2019-08-18
      • 2023-03-30
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多