skip to Main Content

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")
            }),

    );
  }
}

2

Answers


  1. children: [
      ...(BasketDataa.basket?.map((key, value) { // USE DESTRUCTURING
        return Text("test"); // THE RETURN
      }).toList() ?? []), 
      // MORE WIDGETS
    ] 
    
    Login or Signup to reply.
  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);
            }),
          ]
        )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search