-1

I have an inherited widget, I send a Map variable inside this inherited widget, then I am pulling this inherited widget from the sub-widget and put this map variable in the map loop within the build method, but I get an error like This "The element type 'Map<dynamic, dynamic>' can't be assigned to the list type 'Widget'."

here is my code simplified version Please don't bother with syntax mistakes i deleted bunch of unnecessary code

class BasketData extends InheritedWidget {
  BasketData({
    Key? key,
    required this.coffees,
    required this.basket,
    required Widget child,
  }) : super(key: key, child: child);

  final List<Map<String, Object>> coffees;

  Map<String, int>? basket;


  static BasketData of(BuildContext context) {
    final BasketData? result = context.dependOnInheritedWidgetOfExactType<BasketData>();
    assert(result != null, 'No BasketData found in context');
    return result!;
  }

  @override
  bool updateShouldNotify(BasketData old) {
    return false;
  }
}


class _MyHomePageState extends State<MyHomePage> {

  List pages = [
    CoffeePage(),
    BasketPage()
  ];

  Map<String, int> basket = {
    "Americano": 1,

  };



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BasketData(
        coffees: coffees,
        basket: basket,
        child: pages[currentPage],
      ),
          });
        },
      ),
    );
  }
}


class _BasketPageState extends State<BasketPage> {

  @override
  Widget build(BuildContext context) {
    final BasketDataa = BasketData.of(context);
    return Center(
      child: Column(
        children: <Widget>[
           BasketDataa.basket.map((key, value) {  // ERROR IS HERE
                Text("test")
            }),

    );
  }
}
Wiro
  • 65
  • 6
  • `BasketDataa.basket` is a `Map`. You call `.map` on that, which returns another `Map`, which isn't a `Widget` - compiler is correct. `Map` has properties like `.entries` and `.values` that return lists (actually iterables) - perhaps that's what you meant. – Richard Heap Apr 05 '23 at 00:07
  • Do these answers help? https://stackoverflow.com/questions/50441168/iterating-through-a-list-to-render-multiple-widgets-in-flutter/50451020#50451020 – Richard Heap Apr 05 '23 at 00:08
  • Unfortunatly its not – Wiro Apr 05 '23 at 00:18

2 Answers2

2

As suggested by Richard Heap's comment, you should not use map function to map over a Map class. Instead you should use the entries property to generate a list of widget.

So, you can do something like this:

Column(
      children: [
        Text("List Of Map Items"),
        ...BasketDataa.basket!.entries.map<Widget>((MapEntry<String, int> a) {
          return Text(a.key);
        }),
      ]
    )
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
Just a Person
  • 1,276
  • 1
  • 5
  • 23
-1
children: [
  ...(BasketDataa.basket?.map((key, value) { // USE DESTRUCTURING
    return Text("test"); // THE RETURN
  }).toList() ?? []), 
  // MORE WIDGETS
]