Flutter下拉菜單DropdownButton

class BusinessPage extends StatefulWidget {
  @override
  _BusinessPageState createState() => _BusinessPageState();
}

class _BusinessPageState extends State<BusinessPage> {
   List<DropdownMenuItem<String>> sortItems = [];
   String _selectedSort = '排序';

   sortItems.add(DropdownMenuItem(value: '排序', child: Text('排序')));
   sortItems.add(DropdownMenuItem(value: '價格降序', child: Text('價格降序')));
   sortItems.add(DropdownMenuItem(value: '價格升序', child: Text('價格升序')));

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: getList());
  }

  getList() {
    return DropdownButton(
                        value: _selectedSort,
                        items: sortItems,
                        onChanged: changedSort,
                      );
  }

DropdownButton的 value 參數(shù)一定要是包含在 items 參數(shù)中的選項(xiàng),否則會報(bào)如下錯誤:

flutter: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 608 pos 15: 'items == null ||
flutter: items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==
flutter: value).length == 1': is not true.
image.png

如果需要一個未選擇狀態(tài)的默認(rèn)提示,就用hint屬性,同時把value屬性設(shè)為null:

hint: Text(
     '請選擇',
      style: TextStyle(
      fontSize: 28.sp,
      color: Utils.hexColor('999999'),
      ),
),

不想要下劃線就再套一層DropdownButtonHideUnderline:

child: Container(
    alignment: Alignment.center,
    child: DropdownButtonHideUnderline(
        child: DropdownButton(
            value: _selectedSort,
            items: sortItems,
            onChanged: changedSort,
        ),
    ),
),

或者把underline屬性設(shè)置為一個空Container:

underline: Container(),

設(shè)為null是不行的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容