【发布时间】:2021-10-10 04:10:00
【问题描述】:
我想在选择项目时在下拉列表中添加一个清晰的图标。而且,点击清除按钮后,我想清除所选项目。我怎样才能做到这一点?
这不是How to clear the dropdown button in flutter的重复项
谢谢
【问题讨论】:
标签: flutter
我想在选择项目时在下拉列表中添加一个清晰的图标。而且,点击清除按钮后,我想清除所选项目。我怎样才能做到这一点?
这不是How to clear the dropdown button in flutter的重复项
谢谢
【问题讨论】:
标签: flutter
您可以使用DropdownButtonFormField 和suffixIcon 装饰,并根据是否选择某些内容,使用setState 显示或不显示它。
试试这个代码:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: MyDropDownButton(),
),
),
),
);
}
}
class MyDropDownButton extends StatefulWidget {
const MyDropDownButton({Key? key}) : super(key: key);
@override
State<MyDropDownButton> createState() => _MyDropDownButtonState();
}
class _MyDropDownButtonState extends State<MyDropDownButton> {
String? _value;
@override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
value: _value,
decoration: InputDecoration(
hintText: 'select...',
suffixIcon: _value == null
? null
: IconButton(
icon: const Icon(Icons.clear),
onPressed: () => setState(() {
_value = null;
})),
),
onChanged: (newValue) => setState(() {
_value = newValue;
}),
items: <String>['first', 'second', 'third']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
【讨论】: