简体   繁体   中英

Flutter:How to update a UI -stateful widget from another stateful class

How do I update my UI when the value change in another stateful widget?.

I created a stateful class (Test2) which build a widget. Then in my main class, I have a list of Test2 widget. Finally, I am iterating thru the list and rendering the Test2 widget.

However, I want to update a value in one of Test2 widget and then have the main UI update accordingly.

How can I do that?

FILE:test2.dart

class Test2 extends StatefulWidget {
   Test2({this.responseId, this.message});
  final String responseId;
  final String message;
  bool strike =false;

  @override
  _Test2State createState() => _Test2State();
}

class _Test2State extends State<Test2> {
  @override
  Widget build(BuildContext context) {
   return Container(
      child: Text(
              widget.responseId + widget.message,
              style: (widget.strike)?TextStyle(decoration: TextDecoration.none):TextStyle(decoration: TextDecoration.underline)
            ),
    );
  }
}

File :home.dart

MAIN CLASS

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

    class _MyHomePageState extends State<MyHomePage> {
      List<Test2> _counter =List();
      int cnt =0;
      @override
      void initState() { 
        super.initState();
        _counter.add(Test2(message: "message",responseId:"1"));
        _counter.add(Test2(message: "message",responseId:"2"));
        _counter.add(Test2(message: "message",responseId:"3"));
       
      }

In my BUILD METHOD

for(int i=0;i<_counter.length;i++)...[
           _counter[i]
            ],

BUTTON CLICK

void _incrementCounter() {
    for(int i=0;i<_counter.length;i++){
      if(_counter[i].responseId =="1"){
        _counter[i].strike =true;
      }
    }
     setState(() {
    });
  }

You can use ValueNotifier to rebuild the listeners.

Decalre a ValueNotifier<bool> in the Text2 class and initialize it.

ValueNotifier<bool> strikeNotifier = ValueNotifier(false); 

then use ValueListenableBuilder to wrap the widget that you want to rebuild when value of strike changes.

ValueListenableBuilder(valueListenable: strikeNotifier, builder: (_, result, widget) => Text(...),)

And create a method for updating the value of strike , also for comparing the old and new values and update the value of ValueNotifier with the comparison result.

void updateStrike(bool value){
    var result = (strike == value);
    strike = value;
    strikeNotifier.value = result;
  }

So you can update the value of strike with updateStrike() in _incrementCounter() to notify the Text2 widgets for rebuilding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM