Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type 'Future<Map<String, dynamic>> Function()' used in the 'for' loop must implement Iterable - Flutter

I am trying to return Map from Future after taking values from database but I'm unable to print the values. Getting below error while accessing values

The type 'Future<Map<String, dynamic>> Function()' used in the 'for' loop must implement Iterable.

Below is simple code.

class ChefDishes extends StatefulWidget {
  @override
  _ChefDishesState createState() => _ChefDishesState();
}

class _ChefDishesState extends State<ChefDishes> {
 @override
  Widget build(BuildContext context) {
    
     var _chefDishes = DatabaseService().getChefDishList;
    
     return Scaffold(
    .....
          Column(
            children: [
              for (var item in _chefDishes)   // <---- E R R O R   I S   H E R E  
                ListView(children: [
                  Text(item['dishname']),
                  Text(item['dishPrice']),
                ]),
            ],
          )
}

DatabaseService class

class DatabaseService {

  Future<Map<String, dynamic>> getChefDishList() async {
    Map<String, dynamic> chefDishes;
    var result =
        await Firestore.instance.collection('dish').("chefID", isEqualTo: uid).getDocuments();

    result.documents.forEach((eachResult) {
          chefDishes = eachResult.data;
    });

    return chefDishes;
  }
}
like image 238
Faizan Kamal Avatar asked Aug 26 '20 08:08

Faizan Kamal


2 Answers

You are not getting the result from the Future. You are trying to use the Future instead of the map in it.

Also, you are starting this getChefDishList in your build function, which is a big no-no.

Here's one way you can fix this:

class _ChefDishesState extends State<ChefDishes> {
  Map<String, dynamic> _chefDishes;
  @override
  initState() {
    startAsyncInit();
  }
  Future startAsyncInit() async {
    setState(() {
      _chefDishes = await DatabaseService().getChefDishList;
    });
  }
  @override
  Widget build(BuildContext context) {
    
     return Scaffold(
    .....
          Column(
            children: [
              for (var item in _chefDishes)   // <---- E R R O R   I S   H E R E  
                ListView(children: [
                  Text(item['dishname']),
                  Text(item['dishPrice']),
                ]),
            ],
          )
}

Or you can use a FutureBuilder.

like image 90
Gazihan Alankus Avatar answered Oct 11 '22 05:10

Gazihan Alankus


Use this way using forEach

  var usrMap = {"name": "Mr MKM", 'Email': '[email protected]'}; 
  usrMap.forEach((k,v) => print('${k}: ${v}')); 
like image 21
Moumit Avatar answered Oct 11 '22 05:10

Moumit