会更改显示的文本。因此,我拥有带有Switch小部件的Class:
class SwitchWidget extends StatelessWidget{
static bool switchOn = false;
void _onSwitchChanged(bool value) {
switchOn = false;
}
@override
Widget build(BuildContext context) {
return Switch(
onChanged: _onSwitchChanged,
value: switchOn,
);
}
}
switchOn 表示开关是否打开。
然后我让Widget小巫婆将switchOn为true时将我的String文本的文本设置为“ ON”,如果为false,则将其设置为“ OFF”:
class SwichTextWidget extends StatelessWidget{
static String text = "OFF";
@override
Widget build(BuildContext context){
if (SwitchWidget.switchOn == true){
text = "ON";
}
else{
text = "OFF";
}
}
}
在另一堂课中,我现在使用我的小部件:
class MatrixPageOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
...
Row( children:[
Text(" Clock Mode"),
SwitchWidget(),
Text(SwichTextWidget.text),
]//Row children
)
但是如果我使用我的开关,文本将保持关闭状态。我期望它不会像这样工作,但是使它工作的最简单方法是什么? 谢谢您的帮助!
答案 0 :(得分:0)
_onSwitchChanged
的 SwitchWidget
的值设置为false
,与传递的值无关:
void _onSwitchChanged(bool value) {
switchOn = false;
}
将其更改为:
void _onSwitchChanged(bool value) {
switchOn = value;
}
文本将更改。
答案 1 :(得分:0)
扑通的方法是这样的:
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool switch = false;
@override
Widget build(BuildContext context) {
return Center(
child: SwitchListTile(
title: Text('Clock Mode'),
value: switch,
onChanged: (bool value) {
setState(() {
switch = value;
});
},
secondary: Icon(Icons.access_time), // or Text(switch ? "ON" : "OFF") instead of an Icon
),
);
}
}