简体   繁体   English

一次性读取 Firebase Cloud (Dart/Flutter)

[英]One-time Read Firebase Cloud (Dart/Flutter)

I need one-time read Data from Firebase Cloud, thats why I use FutureBuilder in my project (dart/flutter).我需要从 Firebase Cloud 一次性读取数据,这就是我在我的项目(dart/flutter)中使用 FutureBuilder 的原因。 But when the application is started it reads without stopping (as stream).但是当应用程序启动时,它会不停地读取(作为流)。 What should I do to fix this?我该怎么做才能解决这个问题?

class Hello extends StatefulWidget {
  @override
  _HelloState createState() => _HelloState();
}

class _HelloState extends State<Hello> {

  Future getPosts() async{
    QuerySnapshot qn = await FirebaseFirestore.instance.collection("111").get();
    return qn.docs;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text('Hello'),
      ),
      body: FutureBuilder(
        future: getPosts(),
        builder: (context, snapshot){
          if(snapshot.connectionState == ConnectionState.waiting){
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          else{
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index){
                return Text(snapshot.data[index].data()["subject"]);
              },
            );
          }
        },
      ),
    );
  }
}

From the FutureBuilder doc :来自FutureBuilder 文档

The future must have been obtained earlier, eg during State.initState, State.didUpdateConfig, or State.didChangeDependencies.未来必须更早获得,例如在 State.initState、State.didUpdateConfig 或 State.didChangeDependencies 期间。 It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder.在构造 FutureBuilder 时,它不能在 State.build 或 StatelessWidget.build 方法调用期间创建。 If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.如果future和FutureBuilder同时创建,那么每次重建FutureBuilder的parent时,异步任务都会重新启动。

Example :例子 :

  Future<QuerySnapshot> future;

  @override
  void initState() {
    super.initState();
    future = Firestore.instance.collection("111").getDocuments();
  }

  // future : future

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM