Fluter-FutureBuilder-未获取AsyncSnapshot数据 [英] Fluter- FutureBuilder-Not getting AsyncSnapshot data

查看:231
本文介绍了Fluter-FutureBuilder-未获取AsyncSnapshot数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get single string data from firestore database using Future and after getting use that data inside FutureBuilder. But getting null value in snapshot data. Provided the complete code below. Tell me where I am making mistake.

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

I can print the data in fetchPost() function. After getting the data from firestore it getting into 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();
            },
          ),
        ),
      ),
    );
  }
}

推荐答案

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

Change your FutureBuilder with followed code it should work for you

  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
    },
  );

这篇关于Fluter-FutureBuilder-未获取AsyncSnapshot数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆