Flutter - 如何将 Future<bool> 转换为 bool。

8

我有一个返回布尔值的Future方法,并且想将这个方法的返回值用作IconButton的颜色。如果我使用以下代码,我的设备屏幕上会显示错误信息'type'Future'在类型转换中不是'bool'类型的子类'

Future<bool> ifExistInFavoriteList(String url) async {

bool ifExists = false;

SharedPreferences prefs = await SharedPreferences.getInstance(); List my = (prefs.getStringList('myFavoriteList') ?? List());

if (my.contains(url)) { ifExists = true; } else { ifExists = false; }

return ifExists;

}

  bool _isLiked() {
bool a = false;
a = ifExistInFavoriteList(widget.imageUrl) as bool;

return a;

} }

Expanded(
                      child: IconButton(
                        color:
                            _isLiked() ? Colors.deepPurple : Colors.green, 
                        icon: Icon(Icons.category),
                        onPressed: () {
                          //TO-DO
                        },
                      ),
                    )
3个回答

6

一个通用的答案。

假设这是你的函数,它返回 Future<bool>

Future<bool> myFunc() async => true;

获取它的 bool 值,
  1. Use async-await

    void main() async {
      var value = await myFunc(); // value = true
    }
    
  2. Use then:

    void main() {
      bool? value;
      myFunc().then((result) => value = result);
    }
    

3

是的,因为ifExistInFavoriteList(String url)是类型为Future<bool>的函数,所以您需要使用FutureBuilder小部件来获取布尔值。

Expanded(
      child: FutureBuilder(
          future: ifExistInFavoriteList(widget.imageUrl),
          builder: (context, asyncSnapshot){
            if(asyncSnapshot.hasData){
              final _isLiked = asyncSnapshot.data;
              return IconButton(
                color:
                _isLiked() ? Colors.deepPurple : Colors.green,
                icon: Icon(Icons.category),
                onPressed: () {
                  //TO-DO
                },
              );
            }
          return IconButton(
            color:Colors.grey,
            icon: Icon(Icons.category),
            onPressed: () {
              //TO-DO
            },
          );
      },),
    ),

3
你不能简单地将Future强制转换为布尔型。你需要使用await或者then语法从这个future中获取布尔值。但是我建议你使用FutureBuilder,这将是最好的解决方案。
FutureBuilder(future: ifExistInFavoriteList(widget.imageUrl),
              builder:(context, snapshot) {
    Color iconColor = Colors.green;
    if (snapshot.hasData && snapshot.data) {
            iconColor = Colors.purple;
    }
    return IconButton(color: iconColor,
                      icon: Icon(Icons.category),
                      onPressed: () {
                         //TO-DO
                      },
           );
     },
),

如果我这样使用,图标颜色不会改变。请更新您的代码。 onPressed: () { if (snapshot.hasData && snapshot.data) { deleteFromFavoriteList(widget.imageUrl); } else { saveFavoriteList(widget.imageUrl); } - jancooth
如果我想在onPressed中编写一个方法,IconColor没有改变 :( - jancooth
想象一下 Instagram 上的“喜欢”按钮。 - jancooth
@jancooth:如果你想重新绘制(我是指根据新值更改该按钮的状态),你有两个选项,1)使用setState重新绘制该小部件。2)修改该future(首先将future分配给一个变量,并在future builder中使用它,如果您重新创建并将其分配给该变量,它将再次执行代码)。 - Midhun MP
1
@jancooth 请查看此线程:https://dev59.com/11QJ5IYBdhLWcg3wwYpK - Midhun MP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接