Flutter Drop DownMenuItem 小部件

Flutter Drop DownMenuItem Widget

我想在Flutter中开发一个下拉按钮。但是我遇到了跟​​随错误。

════════ 组件库捕获异常═════════════════════════════════ ═══════════════════════ 以下 NoSuchMethodError 被抛出构建 DefaultTextStyle(debugLabel: (englishLike body1 2014).merge(whiteMountainView body1), inherit: false, color: Color(0xffffffff), family: Roboto, size: 14.0, weight: 400, baseline: alphabetic, decoration : TextDecoration.none, softWrap: 以盒子宽度包装,溢出: clip):

getter 'value' 被调用为 null。 接收者:空 尝试调用:值

这是我的代码。

String Selected_Category;
List<String>Categories=["C++","Java","Flutter","Kotlin","PHP","C#"];    
DropdownButton<String>(
        focusColor: Colors.redAccent,
        items: Categories.map(
            (String dropdownStringItem) {
             DropdownMenuItem<String>(
                   value: dropdownStringItem,
                   child:
                   Text(dropdownStringItem),
                   );
        }).toList(),
        onChanged: (value) {
                   setState(() {
                          this.Selected_Category = value;
                     });
               },
       value: Selected_Category,
    ),

请帮我看看我该如何解决这个问题。

提前致谢。

您收到此错误是因为您的 Selected_Category 变量未初始化。

给它一个默认值,你会好的:)

以下是构建下拉按钮的方法:

String dropdownValue = 'One';

@override
Widget build(BuildContext context) {
  return 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(),
  );
}

您收到此错误是因为您没有returning DropDownButton。

您只是缺少 return 个关键字。

return DropdownMenuItem<String>( // return keyword added

您可以设置值:'c++' 或将 selected_category 初始化为任一选项,例如

         Selected_category = 'c++'