我在无状态wigdet里面使用DropdownButton,但我想从另一个有状态的widget改变DropdownButton的值。同样,使用DropdownButton值,我想改变另一个无状态widget的容器颜色。
这是我的第一个无状态widget
List<String> dropdownValues = ['red', 'green', 'blue'];
@override
Widget build(BuildContext context) {
return Container(
child: DropdownButton(
items: dropdownValues
.map((value) => DropdownMenuItem(
child: Text(value),
value: value,
))
.toList(),
onChanged: (String newValue) {},
isExpanded: false,
hint: Text('Chose Color'),
selectedItemBuilder: ,
),
);
}
}
这是我的有状态小部件
bool isLightOn = false;
@override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
padding: new EdgeInsets.all(5.0),
child: Column(
children: <Widget>[
LightBulb(
isLightOn: isLightOn,
),
LightButton(
isLightOn: isLightOn,
onButtonPress: onButtonPress,
),
LightColorSelector(),
],
),
);
}
void onButtonPress() {
if (isLightOn == false) {
setState(() {
isLightOn = true;
});
} else {
setState(() {
isLightOn = false;
});
}
}
}
我如何处理这些问题,如何操作DropdownButton的值?同样,我想通过改变LightBulb的容器颜色来反映该DropdownButton值。
下面是LightBulb类
final bool isLightOn;
LightBulb({this.isLightOn});
@override
Widget build(BuildContext context) {
return Container(
color: isLightOn == false ? Colors.red : Colors.green,
padding: EdgeInsets.all(5.0),
child: isLightOn == false ? Text("OFF") : Text("ON"),
);
}
}
这里是一个完整的工作示例。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> dropdownValues = ['red', 'green', 'blue'];
String selected;
Color color;
@override
Widget build(BuildContext context) {
return Material(
child: Column(children: <Widget>[
DropdownButton<String>(
items: dropdownValues
.map((value) => DropdownMenuItem(
child: Text(value),
value: value,
))
.toList(),
onChanged: (String newValue) {
setState(() {
selected = newValue;
if (newValue == "red") color = Colors.red;
if (newValue == "green") color = Colors.green;
if (newValue == "blue") color = Colors.blue;
});
},
//isExpanded: false,
hint: Text('Chose Color'),
//selectedItemBuilder: ,
),
Container(
color: color != null ? color : Colors.black,
padding: EdgeInsets.all(5.0),
child: selected != null ? Text(selected) : Text("OFF", style: TextStyle(color: Colors.white)),
)
]),
);
}
}