我有一个异步函数,它在收到蓝牙信号时更新一个全局 bool 变量。 每当我更改 bool 变量时,我都想更新一个小部件,但我不知道如何操作。
bool payingAttention = false;
startListening() async {
//code that checks continously
if (thing) {
payingAttention = false;
}
if (otherThing) {
payingAttention = true;
}
}
//...
class PageTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
//this is the widget I need updated
child: payingAttention ? Icon(Icons.sentiment_very_satisfied, size: 200, color: Colors.white,) : Icon(Icons.sentiment_very_dissatisfied, size: 200, color: Colors.white,),
);
}
}
最佳答案
信息在 Flutter 中自上而下流动。这意味着我们将信息从父级传递给子级,通常是在构建过程中。您更新子小部件中的值的方法是在构建时传入新值。由于该值取决于状态,这意味着您需要使用状态管理解决方案来实现这一点。
这意味着您需要更新您的状态,然后使用新值重建您的小部件。最简单的方法是使用有状态小部件并在 setState 调用中更改您的值。那么你需要做什么。
将您的小部件更改为有状态的。如果安装了 VC 代码扩展,请将光标放在无状态类上,然后按 Ctrl + Shift + R。选择转换为有状态。
调用 setState,以便您的小部件使用您的新状态进行重建,将更新后的值传递给您的 child 。
startListening() async {
setState((){
//code that checks continously
if (thing) {
payingAttention = false;
}
if (otherThing) {
payingAttention = true;
}
});
}
关于flutter - 从外部函数更新小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56952072/