I want to Display document ids from cloud firestore in drop down button using future builder in flutter but got error

Viewed 31

here is the code from which I am able to get document ids in collection from cloud firestore

class _MyHomePageState extends State<MyHomePage> {
    final userRef =
  
    FirebaseFirestore.instance.collection('/Exam');
  

@override
Widget build(BuildContext context) {
return Container(
  child: TextButton(
    child: Text('press'),
    onPressed: () {
      userRef.get().then((snapshot) {
        snapshot.docs.forEach((doc) {
          print(doc.id);
        });
      });
    },
  ),
  );
 }
}

I want to convert above code into future builder and map it in drop down button. I convert the above code as follow. Is it correct or not?

FutureBuilder(
  future: db.collection('/Exam').get(),
  builder:
      (BuildContext context, AsyncSnapshot asyncSnapshot) {
    if (asyncSnapshot.hasError)
      return Text("Error: ${asyncSnapshot.error}");
    if (!asyncSnapshot.hasData)
      return const CircularProgressIndicator();

    return DropdownButton<String>(
      isExpanded: true,
      items: asyncSnapshot.data!.docs
          .map(
            (snap) => DropdownMenuItem(
              value: snap.id,
              child: Text(
                snap.id.toString(),
              ),
            ),
          )
          .toList(),
      value: _selectedexam,
      onChanged: (String? newValue) {
        setState(() {
          _selectedexam = newValue!;
          _selectedsemester = null;
          print(_selectedexam);
        });
      },
    );
  }),

If I run above code I get following errors

error pic

error pic on debug console

1 Answers

you need to type cast future builder as below

return FutureBuilder<QuerySnapshot>
Related