【问题标题】:Expected a value of type 'List<DropdownMenuItem<Color>>', but got one of type 'MappedListIterable<Color, DropdownMenuItem<Color>>'预期类型为“List<DropdownMenuItem<Color>>”的值,但得到类型“MappedListIterable<Color, DropdownMenuItem<Color>>”之一
【发布时间】:2020-01-17 17:12:17
【问题描述】:

我正在尝试从下拉菜单中更改主题颜色,但收到此错误:“预期值为 'List>',但得到了一个类型 'MappedListIterable>'

Color  selected ;

MaterialApp(
      theme: ThemeData(primarySwatch: selected),
      home: Scaffold();

 List myColor = [
    Colors.amber,
    Colors.blue,
    Colors.green,
    Colors.black,
  ];

 DropdownButton(
              icon: Icon(Icons.arrow_downward),
              value: selected,
              onChanged: (value){
                setState(() {
                  selected = value;
                });
              },
              items: myColor.map((value)=>DropdownMenuItem(
                value: value,
                child: Text(value.toString()),
              ))
            ),

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    DropdownButton 需要显式类型才能正确匹配其项目。您也没有将map 返回的可迭代对象转回列表:

    // Before, it's type was List<dynamic>
    List<Color> myColor = [ // Add <Color>
      Colors.amber,
      Colors.blue,
      Colors.green,
      Colors.black,
    ];
    

    items: myColor.map(
      (value) => DropdownMenuItem(
        value: value,
        child: Text(value.toString()),
      ),
    ).toList(), // Add toList()
    

    有关详细信息,请参阅DropdownButton docs

    【讨论】:

    • toList() 将 map 的输出展平
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2019-10-05
    • 1970-01-01
    • 2019-11-07
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多