Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 异步等待颤振firestore_Asynchronous_Flutter_Async Await_Google Cloud Firestore - Fatal编程技术网

Asynchronous 异步等待颤振firestore

Asynchronous 异步等待颤振firestore,asynchronous,flutter,async-await,google-cloud-firestore,Asynchronous,Flutter,Async Await,Google Cloud Firestore,我想问一下我的代码是怎么回事 在本例中,假设“Counter”字段为179,如何在打印之前更新我的outside myData class Test { Firestore _firestore = Firestore.instance; var myData; void getData() async { DocumentSnapshot snapshot = await _firestore.collect

我想问一下我的代码是怎么回事

在本例中,假设“Counter”字段为179,如何在打印之前更新我的outside myData

    class Test {
      Firestore _firestore = Firestore.instance;
      var myData;

      void getData() async {
        DocumentSnapshot snapshot =
            await _firestore.collection('Counter').document('Counter').get();
        myData = await snapshot.data['Counter'];
        print('inside $myData');
      }

      void checkMyData() {
        myData = 5;
        getData();
        print('outside $myData');
      } 
    }
控制台:

颤振:外部5


颤振:在179中,您必须使
getData()
返回
Future
如下:

Future getData() async {
FutureBuilder(
  future: getData(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text('value: ${snapshot.data}');
    } else if (snapshot.hasError){
      return Text('error: ${snapshot.error}');
    }
    return Text('loading...');
  },
)
所以你可以这样做:

getData().then((value) {
  print('value: $value');
}).catchError((error) {
  print('error: $error');
});
但您可能希望在到达时使用
FutureBuilder
来显示信息,如下所示:

Future getData() async {
FutureBuilder(
  future: getData(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text('value: ${snapshot.data}');
    } else if (snapshot.hasError){
      return Text('error: ${snapshot.error}');
    }
    return Text('loading...');
  },
)

然后我可以问一下,如果我有两个变量要返回怎么办?你应该有一个包含这两个变量的对象