how to pass a variable as a parameter to a widget two, modify it there, and return the modified value to widget one, Flutter

Viewed 248

how to pass a variable as a parameter to a widget two, modify it there, and return the modified value to widget one. I need to change the value of the variable when I click the "Change it" button, and that change is reflected in widget one.

class FirstWidget extends StatefulWidget {
  @override
  _FirstWidgetState createState() => _FirstWidgetState();
}
class FirstWidgetState extends State<FirstWidget> {
String c = 'start';
        @override
        Widget build(BuildContext context){
            return Container(
                child: SecondWidget(variable: c),
            );
        }
    }
    class SecondWidget extends StatefulWidget {
    String variable;
    SecondWidget({ this.variable });
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}
    class SecondWidgetState extends State<SecondWidget> {
        @override
        Widget build(BuildContext context){
            return Container(
                child: RaisedButton(child:Text('Change it'), onPressed: () {widget.variable = 'end';}),

            );
        }
    }

1 Answers

It is possible to implement it easily with a callback, meaning you pass a function to your second widget, and when the button is clicked you call the function, this way you can modify whatever you want in the first widget.

Like this:

class FirstWidget extends StatefulWidget {
  @override
  _FirstWidgetState createState() => _FirstWidgetState();
}
class FirstWidgetState extends State<FirstWidget> {
String c = 'start';
        @override
        Widget build(BuildContext context){
            return Container(
                child: SecondWidget(variable: c, onChange: (newVal) {
                    setState(() {c = newVal;});
                 }),
            );
        }
    }
    class SecondWidget extends StatefulWidget {
    String variable;
    final onChange;

    SecondWidget({ this.variable, this.onChange });
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}
    class SecondWidgetState extends State<SecondWidget> {
        @override
        Widget build(BuildContext context){
            return Container(
                child: RaisedButton(child:Text('Change it'), onPressed: () {widget.onChange('end');}),

            );
        }
    }
Related