我有一个继承的小部件,我在这个继承的小部件内部发送一个Map变量,然后我从子小部件中拉出这个继承的小部件,并将这个地图变量放在构建方法中的地图循环中,但是我得到一个错误,如"元素类型'Map<dynamic,>'不能分配给列表类型' widget '"。
这是我的代码简化版本请不要担心语法错误,我删除了一堆不必要的代码
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")
}),
);
}
}
正如Richard Heap的注释所建议的那样,您不应该使用map函数来映射map类。相反,您应该使用entries属性来生成一个小部件列表。
那么,你可以这样做:
Column(
children: [
Text("List Of Map Items"),
...BasketDataa.basket!.entries.map<Widget>((MapEntry<String, int> a) {
return Text(a.key);
}),
]
)
children: [
...(BasketDataa.basket?.map((key, value) { // USE DESTRUCTURING
return Text("test"); // THE RETURN
}).toList() ?? []),
// MORE WIDGETS
]