[英]How to change DropdownButton selected option color?
I have a DropdownButton in Flutter and i want to change the color of the selected option (see image).我在 Flutter 中有一个 DropdownButton,我想更改所选选项的颜色(见图)。 Default color is grey.
默认颜色为灰色。 I could not find a parameter of DropdownButton to change that.
我找不到 DropdownButton 的参数来改变它。 I tried
selectedRowColor
in ThemeData but it does not affect that color.我在 ThemeData 中尝试了
selectedRowColor
,但它不会影响该颜色。 Is it possible to change that color?可以改变那个颜色吗?
Minimal reproducible example:最小的可重现示例:
import 'package:flutter/material.dart';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
highlightColor: Colors.red,
),
home: MyHome(),
);
}
}
class MyHome extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
List<String> options = ['A', 'B', 'C', 'D'];
String selectedOption;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton(
hint: Text('Please choose an option'),
value: selectedOption,
onChanged: (String newValue) {
setState(() {
selectedOption = newValue;
});
},
items: options.map((option) {
return DropdownMenuItem(
child: Text(option),
value: option,
);
}).toList(),
),
),
);
}
}
.
.
].map<DropdownMenuItem<String>>((String value) {
return GestureDetector(
onTap: () {
setState() {
_selectedItemValue = value;
}
} ,
child:DropdownMenuItem<String>(
value: value,
child: Container(
color: value == _selectedItemValue ? Colors.blue : Colors.white,
child: new Text(
value,
style: TextStyle(color: Colors.white),
),),
),);
}).toList(),
I found the solution.我找到了解决方案。 The
focusColor
in ThemeData
is affecting this color. ThemeData
中的focusColor
正在影响此颜色。
I get the desired results if i wrap the DropdownButton
with a Theme
Widget and change the focusColor
parameter.如果我用
Theme
小部件包装DropdownButton
并更改focusColor
参数,我会得到所需的结果。 Or setting the focusColor
directly in material apps theme.或者直接在材质应用主题中设置
focusColor
。
Like this:像这样:
//...
Theme(
data: Theme.of(context).copyWith(focusColor: Colors.red),
child: DropdownButton(
hint: Text('Please choose an option'),
value: selectedOption,
onChanged: (String newValue) {
setState(() {
selectedOption = newValue;
});
},
items: options.map((option) {
return DropdownMenuItem(
child: Text(option),
value: option,
);
}).toList(),
),
)
//...
result: enter image description here结果:在此处输入图像描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.