Flutter DropdownButton显示一些奇怪的行为:禁用时,它显示小部件disabledHint
而不是所选值(必须通过将onChanged
设置为null来完成)。
如何显示所选值?
这是我的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DropdownButton disable problem',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _enabled = true;
int value;
List<DropdownMenuItem<int>> items = [
DropdownMenuItem(
value: 11,
child: Text('asdf'),
),
DropdownMenuItem(
value: 27,
child: Text('qwert'),
),
DropdownMenuItem(
value: 31,
child: Text('yxcv'),
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DropdownButton problem'),
),
body: Center(
child: Column(
children: <Widget>[
Text(
'Disabling the DropdownButton looses its selection',
),
Switch(
onChanged: (v) => setState(() {
_enabled = v;
}),
value: _enabled,
),
DropdownButton(
items: items,
onChanged: _enabled
? (v) => setState(() {
value = v;
})
: null,
value: value,
)
],
),
),
);
}
}
答案 0 :(得分:1)
如果您将List
项作为List
的{{1}},并从中生成Map
,则可以更轻松地识别所选内容并将其设置为DropdownMenuItems
:
disabledHint
答案 1 :(得分:0)
从flutter dropDown api文档中:
If the onChanged callback is null or the list of items is null then the dropdown
button will be disabled, i.e. its arrow will be displayed in grey and it will not
respond to input. A disabled button will display the disabledHint widget if it is non-
null. However, if disabledHint is null and hint is non-null,
the hint widget will instead be displayed.`