【问题标题】:Flutter Error: A value of type 'Future<bool>' can't be assigned to a variable of type 'bool' when get value form function Future<bool>Flutter 错误:当从函数 Future<bool> 获取值时,无法将“Future<bool>”类型的值分配给“bool”类型的变量
【发布时间】:2021-03-23 16:27:23
【问题描述】:

我在获取值形式函数 Future 时遇到问题
我下面有一个函数

Future<bool> checkstr(String str) async {
     bool result = await check(str);
     if (result == null) {
         return false;
     } else {
         return true;
     }
}

当我得到并检查值遇到错误时

Expanded(
      child: model.isBusy
           ? CircularProgressIndicator()
           : ListView.builder(   
                  itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                          model.checkstr(str)       //<------ error this line
                          ? title: Text('true')
                          : title: Text('false'),
                    }),
          ),

错误

 Flutter Error: A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'

请帮帮我。

【问题讨论】:

  • 您不能直接调用该方法,因为您需要等待结果。尝试使该方法不再是未来或在另一个地方进行调用并在使用该值之前等待结果。
  • 发布您的check(str) 功能。是未来吗?你为什么要等它?根据您的回答,您主要有两种解决方案之一。

标签: flutter dart boolean future getvalue


【解决方案1】:

您必须使用FutureBuilder,因为checkstr()未来

Expanded(
    child: model.isBusy
        ? CircularProgressIndicator()
        : ListView.builder(itemBuilder: (BuildContext context, int index) {
            return FutureBuilder(
              future: checkstr(str),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting)
                  return CircularProgressIndicator();
                return ListTile(
                    title: Text(snapshot.data ? 'true' : 'false'));
              },
            );
          }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2021-11-24
    • 2021-10-16
    • 2021-10-10
    • 2019-07-08
    • 2021-12-31
    • 2020-08-23
    • 2021-04-07
    相关资源
    最近更新 更多