0

I have an asynchronous function that updates a global boolean variable when it gets a Bluetooth signal. I want to update a widget whenever I change the boolean variable but I don't know how.

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,),
   );
 }
}
0

1 Answer 1

2

Information flows top down in Flutter. That means we pass the information from the parent to the children, usually on construction. The way you'd update the value in your child widget is by passing in the new one on construction. Since the value is dependent on state it means you'll need to use a state management solution to achieve this.

What that means is that you need to update your state and then rebuild your widget with the new value. The easiest way to do that is by using a stateful widget and changing your value in the setState call. So what you need to do it.

  1. Change your widget to be stateful. Put the cursor on your Stateless class and press Ctrl + Shift +R if you have the VC code extension installed. Select convert to stateful.

  2. Call setState so your widget rebuilds with your new state passing down your updated value to your child.

startListening() async {
   setState((){
     //code that checks continously
     if (thing) {
      payingAttention = false;
     }
     if (otherThing) {
      payingAttention = true;
     }
   });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.