为了在Flutter中以编程方式清除DropdownButton,您需要了解其内部状态
下面是如何实现它的步骤:
class MyDropdown extends StatefulWidget {
@override
_MyDropdownState createState() => _MyDropdownState();
}
class _MyDropdownState extends State<MyDropdown> {
GlobalKey<_MyDropdownState> _dropdownKey = GlobalKey();
String _selectedItem;
@override
Widget build(BuildContext context) {
// ...
}
}
String _selectedItem;
void _onSelectChanged(String newValue) {
setState(() {
_selectedItem = newValue;
});
}
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
key: _dropdownKey,
value: _selectedItem,
onChanged: _onSelectChanged,
items: [
DropdownMenuItem(value: 'Item 1', child: Text('Item 1')),
DropdownMenuItem(value: 'Item 2', child: Text('Item 2')),
DropdownMenuItem(value: 'Item 3', child: Text('Item 3')),
],
);
}
void clearDropdown() {
setState(() {
_selectedItem = null;
});
}
现在,每当你调用clearDropdown()
方法时,DropdownButton的值将被清空并触发UI重建。
以下是完整示例代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('DropdownButton Example')),
body: MyDropdown(),
),
);
}
}
class MyDropdown extends StatefulWidget {
@override
_MyDropdownState createState() => _MyDropdownState();
}
class _MyDropdownState extends State<MyDropdown> {
GlobalKey<_MyDropdownState> _dropdownKey = GlobalKey();
String _selectedItem;
void _onSelectChanged(String newValue) {
setState(() {
_selectedItem = newValue;
});
}
void clearDropdown() {
setState(() {
_selectedItem = null;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
DropdownButton<String>(
key: _dropdownKey,
value: _selectedItem,
onChanged: _onSelectChanged,
items: [
DropdownMenuItem(value: 'Item 1', child: Text('Item 1')),
DropdownMenuItem(value: 'Item 2', child: Text('Item 2')),
DropdownMenuItem(value: 'Item 3', child: Text('Item 3')),
],
),
ElevatedButton(
onPressed: clearDropdown,
child: Text('Clear Dropdown'),
),
],
);
}
}
现在,当你点击"Clear Dropdown"按钮时,DropdownButton的值将被清空。
领取专属 10元无门槛券
手把手带您无忧上云