One-time Read Firebase Cloud (Dart/Flutter)

Viewed 315

I need one-time read Data from Firebase Cloud, thats why I use FutureBuilder in my project (dart/flutter). 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"]);
              },
            );
          }
        },
      ),
    );
  }
}

1 Answers

From the FutureBuilder doc :

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. 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.

Example :

  Future<QuerySnapshot> future;

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

  // future : future
Related