如何在颤振中改变动态创建的按钮状态?



我想在flutter中创建mqtt应用程序。其中一个功能是添加新设备的能力。基本上,应用程序需要控制和监控设备的能力。所以我尝试创建功能来动态创建按钮来控制设备。

_create_button(String topic, String on, String off) {
String id = uuid.v4();
print('create button $id');
buttons_switches[id] = true;
Widget _button =  ElevatedButton(
style: style,
onPressed: () {
publist_button_onpress (topic, on, off, id);
},
child:
Row( mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('$topic хз'),
Icon(Icons.circle, color: _colors),
]
)
);
return _button;
}

我动态创建按钮,然后将这个按钮添加到我想要显示的按钮数组

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: buttons_dynamic,
)

这个按钮实际上工作,但有一个问题:我不知道如何改变这个按钮的状态例如,将按钮的颜色从绿色更改为红色

有谁能帮我一下吗?

要改变颤振状态,最好使用setState方法。要使用它,您的类必须为StatefulWidget。一旦您使用setStates更改了值并通过方法中的参数传递。例如,改变。颜色. .在ElevatedButton中使用ButtonStyle。您的方法将如下所示:

_create_button(String topic, String on, String off, Color yourColor,) {
String id = uuid.v4();
print('create button $id');
buttons_switches[id] = true
Widget _button =  ElevatedButton(
style: ButtonStyle(   //use ButtonStyle to change the visual properties to your button
padding: MaterialStateProperty.all(EdgeInsets.all(12)),
elevation: MaterialStateProperty.all(0), //shows a shadow in your button
backgroundColor: MaterialStateProperty.all<Color>(yourColor),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
onPressed: () {
publist_button_onpress (topic, on, off, id);
},
child:
Row( mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('$topic хз'),
Icon(Icons.circle, color: _colors),
]
)
);
return _button;
}

希望我帮到你了。问候。

最新更新