[英]how to use 'dropdownbutton'?
當我將 DropdownButton 代碼插入到我的代碼中時出現錯誤。 在包含主體的代碼之外,他們將其聲明為 class,當我將聲明的 class 放入代碼中時,出現如下錯誤消息。
'_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 890 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1': There should be exactly one item with [DropdownButton]'s value: sex.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)'
下面是我的代碼。
.....
....
onChanged: (_) {
setState(() {});
}
),
SelectButton(),
],
),
),
class SelectButtonState extends State<SelectButton> {
final List<String> _valueList = ['M', 'F'];
String _selectedValue = 'sex';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: _selectedValue,
items: _valueList.map((value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedValue = value!;
});
},
);
}
}
class SelectButton extends StatefulWidget {
const SelectButton ({Key? key}) : super(key: key);
@override
State<SelectButton> createState() => SelectButtonState();
}
我想做愛 select 按鈕...
您的 _valueList 僅包含 ['M', 'F'] 並且您正在從中創建一個 DropDownButton。 當編譯器發現 _valueList 數組中不可用的初始值為“Select Sex”時,您會收到 NULL 錯誤。
解決方案 -> 使用“選擇性別”作為下拉提示。 在初始聲明中將 _selectedValue 保留為 null,以便顯示提示。
使用 null 檢查將 _selectedValue 設置為 null:
String? _selectedValue = null;
試試這個
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: const Scaffold(
body: Center(
child: aa(),
),
),
);
}
}
class aa extends StatefulWidget {
const aa({Key? key}) : super(key: key);
@override
State<aa> createState() => _aaState();
}
class _aaState extends State<aa> {
String selectedNumber = '1';
List numberList = ['1', '2', '3', '4'];
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(8)),
child: DropdownButton(
style: const TextStyle(color: Colors.black),
dropdownColor: Colors.white,
underline: Container(),
value: selectedNumber,
onChanged: (value) {
selectedNumber = value! as String;
setState(() {});
},
items: numberList.map((itemone) {
return DropdownMenuItem(
value: itemone,
child: Center(
child: Text(
itemone,
style: const TextStyle(
color: Colors.black, fontWeight: FontWeight.w700),
),
),
);
}).toList(),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.