Home > Software design >  I am using clear method inside future function to avoid duplication but even though it duplicates in
I am using clear method inside future function to avoid duplication but even though it duplicates in

Time:11-11

I am creating a demo page where I want to display all user's id in a page..and for that I have created a method that adds all user's id to a list array..

I do clear the array before adding ids...but even though it adds double entries on refresh or hot reload

here is my basic code


class _WelcomePageState extends State<WelcomePage> {
  List<String> templist=[];
  Future getAllDocumentIds() async{
    templist.clear();
    await FirebaseFirestore.instance.collection('users').get().then((snapshot) {
      return snapshot.docs.forEach((document) {
        templist.add(document.reference.id.toString());
      });
    });



  }
  @override
  Widget build(BuildContext context) {
    final user=FirebaseAuth.instance.currentUser!;
    return Scaffold(
      appBar: AppBar(
        title: Text('Showing All Users'),
        actions: [IconButton(onPressed: (){
          FirebaseAuth.instance.signOut();
        }, icon: Icon(Icons.logout))],

      ),
        body: Column(

          mainAxisAlignment: MainAxisAlignment.start,
          children: [
          Padding(
            padding: const EdgeInsets.only(right: 20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
              Text('Welcome, '),
              SizedBox(width: 10,),
              Text(user.email.toString(),style: TextStyle(fontSize: 20,color: Colors.blue),),
            ],),

          ),

            Expanded(child: FutureBuilder(
              future:getAllDocumentIds() ,
              builder: (context,snapshot){
                return ListView.builder(
                    itemCount: templist.length,
                    itemBuilder: (context,index){
                      return Text(templist[index].toString());
                    });
                
              },
            ))

        ],),);
  }
}

CodePudding user response:

Use snapshot.data to get the list of IDs. Check out the official docs here. Remember to handle all the states the Futurebuilder emits eg. show a loader as you wait for data from Firebase.

Firebase being a real-time database, a Streambuilder would work better than a futureBuilder

  • Related