Home > OS >  I have to refresh page for getting data in flutter listview.builder
I have to refresh page for getting data in flutter listview.builder

Time:09-01

I am fetching records from firebase collection with a UDF and calling this UDF inside Widget build,

it has to refresh to show data,

looks like. widget build before getting data....how to prevent loading widget build until data is not fetched ...


class _DemoPage2State extends State<DemoPage2> {

  List<String> list = [];

  void getusers() async
  {
    final snapshot = await FirebaseFirestore.instance
        .collection("users").get();

    list.clear();
    for (int x = 0; x < snapshot.docs.length; x  ) {
      list.add(snapshot.docs[x].id);
    }
  }


  @override
  Widget build(BuildContext context) {
    getusers();
    return Scaffold(
      body: ListView.builder(
          itemCount: list.length,
          itemBuilder: (context, index) {
            return Container(
                padding: EdgeInsets.all(20),
                child: Text(list[index].toString()));
          }),

    );
  }
}

CodePudding user response:

Try using StreamBuilder

 final myStream =
      FirebaseFirestore.instance.collection("users").snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder(
      stream: myStream,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(itemBuilder: itemBuilder);
        }
        return CircularProgressIndicator();
      },
    ));
  }
  • Related