Fluter- FutureBuilder-未获取AsyncSnapshot数据

时间:2019-03-24 07:14:07

标签: firebase flutter

我正在尝试使用Future从firestore数据库中获取单字符串数据,并在FutureBuilder中使用该数据之后。但是在快照数据中获得null值。在下面提供了完整的代码。告诉我我在哪里犯错。

我可以在fetchPost()函数中打印数据。从Firestore中获取数据后,它进入FutureBuilder

但是快照数据为空-AsyncSnapshot<String>(ConnectionState.done, null, null)

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future <String>fetchPost() async  {
  final DocumentReference documentReference = Firestore.instance.document("myData/dummy");
   documentReference.get().then((datasnapshot){
    if(datasnapshot.exists){
        print("get data" +datasnapshot.data['url']); ///this printing data //in console
        return datasnapshot.data['url'];


    }
  }).catchError((e){
    print("Error");
    print(e);
  });

}


void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<String> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: post,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
              print ("snapshot has data");
              print (snapshot); // this printing 'AsyncSnapshot<String>(ConnectionState.done, null, null)'
              print (snapshot.data);// this printing null
              if (snapshot.hasData) {

                return Text(snapshot.data);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

使用以下代码更改您的FutureBuilder,它应该对您有用

  FutureBuilder(
    future: Firestore.instance.collection("myData").document("dummy").get(), 
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return Text('Press button to start.');
        case ConnectionState.active:
        case ConnectionState.waiting:
          return Text('Awaiting result...');
        case ConnectionState.done:
          if (snapshot.hasError)
            return Text('Error: ${snapshot.error}');
          return Text('Result: ${snapshot.data}');
          // You can reach your snapshot.data['url'] in here
      }
      return null; // unreachable
    },
  );

答案 1 :(得分:0)

我使用示例Widget构建采取了更为详细的方法,并展示了如何显示进度消息。

    child: FutureBuilder<String>(
        future: post,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                        switch (snapshot.connectionState){
                          case ConnectionState.none:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'No Connection Message')
                                    )
                                )
                            );
                          case ConnectionState.active:
                          case ConnectionState.waiting:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'Loading_message..'
                                    )
                                )
                            );
                          case ConnectionState.done:
                            if (snapshot.data.isEmpty){
                              return Container(
                                  child: Center(
                                      child: Text(
                                          'No Data available'
                                      )
                                  )
                              );
                            } else {
                              return ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return ListTile(
                                      title: Text(snapshot.data[index].displayValue,
                                          softWrap: true),
                                      onTap: () {
                                        Navigator.push(context, new MaterialPageRoute(builder: (context) {
                                          return DetailItem(dataItem: snapshot.data[index]);
                                        }));
                                      },
                                    );
                                  }
                              );
                            }
                        }
                        return null;
                      }

享受!