如何从Flutter FutureBuilder中的AsyncSnapshot <string>获取String?

时间:2018-04-09 00:18:57

标签: async-await dart future flutter

我想要从NetworkImage(url)加载一张图片。我在初始函数中填充Future<String> images;变量,现在我无法让FutureBuilder将其作为字符串读取。我在网址上收到错误为&#34;参数类型AsyncSnapshot无法分配给参数类型String&#34;这是我的代码......

Future<String> images;

Future<Null> getData() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser;
    user = await FirebaseAuth.instance.currentUser;
    var userid = user.uid;
    await fb.child('users/${userid}').onValue.listen((Event event) {
      if (event.snapshot.value != null) {
        name = event.snapshot.value['displayName'];
        images = event.snapshot.value['image'];
      } else {
        name = "MyFavKPop";
      }
    });
  }

new FutureBuilder<String>(
  future: images, // a Future<String> or null
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return new Text('Press button to start');
      case ConnectionState.waiting: return new Text('Awaiting result...');
      default:
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        else
          return new CircleAvatar(
            backgroundImage: new NetworkImage(snapshot.data.toString()) // getting NetworkImageError ..looking for String not Future<String>,
            radius:  75.0,
          );
     }
 }),

1 个答案:

答案 0 :(得分:1)

结果数据是AsyncSnapshot.data,而不是快照本身的实例。在您的示例中,案例应为:

switch (snapshot.connectionState) {
  case ConnectionState.none:
    return new Text('Press button to start');
  case ConnectionState.waiting:
    return new Text('Awaiting result...');
  default:
    if (snapshot.hasError)
      return new Text('Error: ${snapshot.error}');
    else {
      return new CircleAvatar(
        backgroundImage: new NetworkImage(snapshot.data),
        radius:  75.0,
      );
    }
}

编辑:第二个问题是您没有正确创建images - 您正在为未来分配字符串。而是在getData方法完成运行时尝试使用完成符来创建Future。

Completer<String> _imageCompleter = new Completer<String>();
Future<String> get images => _imageCompleter.future;

Future<Null> getData() async {
  ...
  _imageCompleter.complete(event.snapshot.value['image']);
}