【问题标题】:How to fix type 'Future<dynamic>' is not a subtype of type 'String' Flutter如何修复“Future<dynamic>”类型不是“String”Flutter 类型的子类型
【发布时间】:2019-08-04 15:49:23
【问题描述】:

这里是 Flutter 初学者;我收到此错误:type 'Future&lt;dynamic&gt;' is not a subtype of type 'String'

从 Firebase 存储中获取下载 url 的函数

_getImageUrl(var fileName) async {
  print(fileName);
  final StorageReference ref = FirebaseStorage.instance.ref().child('categories/' + fileName);
  Uri downloadUrl = await ref.getDownloadURL();
  var url = downloadUrl.toString();
  return url;
}

我调用函数的地方

child:  Image(
  image:  AdvancedNetworkImage(
    _getImageUrl(menuItem['image'].toString()),
    timeoutDuration: Duration(minutes: 1),
    useDiskCache: true,
    cacheRule: CacheRule(maxAge: const Duration(days: 7)),
  ),
  height: mediaQuery.size.width * 0.22,
  width: mediaQuery.size.width * 0.22,
),

【问题讨论】:

标签: dart flutter


【解决方案1】:

首先Flutter在asynchronous函数没有完成的时候返回一个Future&lt;type&gt;,完成后会返回type类型的数据。您犯的错误是从synchronous 函数调用asynchronous。虽然 dart 将执行函数 asynchronously(您可以通过打印来自 asynchronous 函数的 url 来验证这一点)。
但是您调用它的地方并不是等待 asynchronous 函数完成。
我希望现在已经清楚了。
如需了解更多信息,请访问 Asynchronous Programming

【讨论】:

    【解决方案2】:

    从build 方法(或builder 闭包)返回时,您不能使用async/await。任何时候在构建小部件树时都有异步,最好使用FutureBuilder:

    child: FutureBuilder<String>(
      future: _getImageUrl(menuItem['image'].toString()),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Image(
            image: AdvancedNetworkImage(
              snapshot.data,
              timeoutDuration: Duration(minutes: 1),
              useDiskCache: true,
              cacheRule: CacheRule(maxAge: const Duration(days: 7)),
            ),
            height: mediaQuery.size.width * 0.22,
            width: mediaQuery.size.width * 0.22,
          );
        }
        return CircularProgressIndicator();
      }
    ),
    

    或者,您可以为此使用StatefulWidget,但它更多的是样板。如果您有兴趣,可以在https://flutterigniter.com/build-widget-with-async-method-call/ 获取更多详细信息和现场示例。

    【讨论】:

      【解决方案3】:

      你的 _getImageUrl 应该返回一个 Future&lt;String&gt; 。

      【讨论】:

      • 现在我得到这个错误'参数类型'Future'不能分配给参数类型'String'。'
      • 在调用这个函数之前使用await
      猜你喜欢
      • 2020-12-09
      • 2021-06-20
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2019-08-18
      • 2023-03-30
      • 2019-12-05
      • 2021-01-03
      相关资源
      最近更新 更多