【问题标题】:The argument type 'Future<bool>' can't be assigned to the parameter type 'bool'参数类型“Future<bool>”不能分配给参数类型“bool”
【发布时间】:2021-04-07 18:08:17
【问题描述】:

我是 Flutter 的初学者

我尝试从 Future 类型函数中获取布尔值

这是我的 Dart 语言编码文件

我从第 104 行收到以下错误

参数类型'Future'不能赋值给参数类型'bool'

代码

isFavorite: _viewForFavorite(photoModel.id),

完整代码

import '../screens/detailView.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:favorite_button/favorite_button.dart';
import '../models/photoSearch.dart';
import 'package:flutter/material.dart';

Widget gridPhotosList(BuildContext context, List<Photo> listPhotos) {
  _viewForFavorite(int photoID) async {
    final prefs = await SharedPreferences.getInstance();
    final myStringList = prefs.getStringList('fav_list') ?? [];
    final boolValue = myStringList.contains(photoID.toString());
    if (boolValue == true) {
      return true;
    } else {
      return false;
    }
  }

  _addForFavorite(int photoID) async {
    final prefs = await SharedPreferences.getInstance();
    final myStringList = prefs.getStringList('fav_list') ?? [];
    myStringList.add(photoID.toString());
    prefs.setStringList('fav_list', myStringList);
  }

  _removeForFavorite(int photoID) async {
    final prefs = await SharedPreferences.getInstance();
    final myStringList = prefs.getStringList('fav_list') ?? [];
    myStringList.remove(photoID.toString());
    prefs.setStringList('fav_list', myStringList);
  }

  var size = MediaQuery.of(context).size;
  final double itemHeight = (size.height - kToolbarHeight) / 2;
  final double itemWidth = (size.width / 2);
  return Container(
    padding: EdgeInsets.symmetric(horizontal: 16),
    child: GridView.count(
      crossAxisCount: 2,
      mainAxisSpacing: 5.0,
      crossAxisSpacing: 5.0,
      padding: const EdgeInsets.all(5.0),
      childAspectRatio: (itemWidth / itemHeight),
      physics: ClampingScrollPhysics(),
      shrinkWrap: true,
      children: listPhotos.map((Photo photoModel) {
        return GridTile(
          footer: GridTileBar(
            subtitle: Text(photoModel.photographer),
            backgroundColor: Colors.black38,
          ),
          child: Stack(
            children: [
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DetailView(
                        imgPath: photoModel.src.portrait,
                        original: photoModel.src.original,
                        imgID: photoModel.id,
                        photoGrapher: photoModel.photographer,
                      ),
                    ),
                  );
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Stack(
                    children: [
                      Hero(
                        tag: photoModel.src.portrait,
                        child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          child: CachedNetworkImage(
                            imageUrl: photoModel.src.portrait,
                            placeholder: (context, url) => Center(
                              child: CircularProgressIndicator(),
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Align(
                alignment: Alignment.topRight,
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(25),
                    ),
                  ),
                  width: 40,
                  height: 40,
                  child: Center(
                    child: FavoriteButton(
                      isFavorite: _viewForFavorite(photoModel.id),
                      iconSize: 15,
                      valueChanged: (_isFavorite) {
                        if (_isFavorite) {
                          _addForFavorite(photoModel.id);
                        } else {
                          _removeForFavorite(photoModel.id);
                        }
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }).toList(),
    ),
  );
}

任何人都可以在此代码上找到问题

感谢您的进阶

【问题讨论】:

标签: flutter dart future


【解决方案1】:

如下所示更改您的小部件

Center(
      child:
      FutureBuilder(
        future: _viewForFavorite(photoModel.id),
        builder: (c,s){
          if(s.hasData){
            var newBool = s.data;
            return FavoriteButton(
              isFavorite: newBool,
              iconSize: 15,
              valueChanged: (_isFavorite) {
                if (_isFavorite) {
                  _addForFavorite(photoModel.id);
                } else {
                  _removeForFavorite(photoModel.id);
                }
              },
            ) ;
          }else {
            return Center(child: CircularProgressIndicator());
          }
        },
      )
    )

【讨论】:

    【解决方案2】:

    当你进入 await 时,你已经将这些函数声明为 Future

    _viewForFavorite(int photoID) async { 实际上这与您的返回语句相同 Future&lt;bool&gt; _viewForFavorite(int photoID) async {

    所以你要么需要使用 FutureBuilder 要么在调用这些函数时使用 await

    【讨论】:

      【解决方案3】:

      您的_viewForFavorite 方法是异步的,您在构建方法中调用它时不带前缀关键字await

      isFavorite: await _viewForFavorite(photoModel.id),
      

      因此,您得到的是 Future&lt;bool&gt; 而不是 Bool

      您将遇到另一个问题,因为您无法在构建方法中直接调用异步方法。但是你可以使用 FutureBuilder 来解决这个问题。

      【讨论】:

        猜你喜欢
        • 2020-08-23
        • 2021-10-16
        • 2021-10-10
        • 2021-11-24
        • 2021-07-06
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多