首页 > 解决方案 > 元素类型“String”不能分配给列表类型“DropdownMenuItem”'

问题描述

我想用一些字符串填充 Flutter 中的 DropdownButton,但出现错误

The element type 'String' can't be assigned to the list type 'DropdownMenuItem<String>' 关于用字符串归档列表

这是我的代码片段:

DropdownButton<String>(
  value: filter.getFilterPersonality(),
  onChanged: (String newValue){filter.setFilterPersonality(newValue);},
  items: ["-"],
),

我究竟做错了什么?

标签: flutterdart

解决方案


items应该是 a Listof DropdownMenuItem<String>not a List<String>,只有“-”。

DropdownButton<String>(
      value: dropdownValue,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String newValue) {
        setState(() {
          dropdownValue = newValue;
        });
      },
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );

见这里: https ://api.flutter.dev/flutter/material/DropdownMenuItem/DropdownMenuItem.html


推荐阅读