Sunshine
Sunshine

Reputation: 344

Flutter- Passing Data between Custom Widgets inside column

I'm stuck with a WidgetA() which calculates a String but I'd like to pass this string to WidgetB() - how do I pass the updated data to WidgetB ?

return Column(
  children: [
    
         WidgetA() // calculates value
         WidgetB() // needs to use this value 

  ],
);

Widget A is a costum Class Stateful Widget

Upvotes: 0

Views: 186

Answers (2)

fravolt
fravolt

Reputation: 3001

The most obvious way, to me, to do this is to store the data in the state of the parent widget. You could then provide WidgetA with a callback to set this state, and provide WidgetB with the value:

int value;

setValue(int newValue) {
    setState(() {
      value = newValue;
    });
}

return Column(
  children: [
    
         WidgetA(callback: (int newValue) => this.setValue(newValue)) // calculates value
         WidgetB(value: this.value) // needs to use this value 

  ],
);

WidgetA and WidgetB could then look something like the following:

class WidgetA extends StatelessWidget {
  final Function callback;

  // get the callback as a named argument
  WidgetA({required this.callback});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: () {
          print('The button was pressed!');
          // get the value and call the callback with it
          callback(42);
        },
        child: Text('Press me!'));
  }
}

class WidgetB extends StatelessWidget {
  final int value;

  WidgetB({required this.value});

  @override
  Widget build(BuildContext context) {
    return Text('The number is $value');
  }
}

Depending on the value and how often it's updated, using some sort of storage like shared preferences for the value is also possible.

Upvotes: 2

Create a shared memory, for example, a class, and save the value to a class variable.

class SharedMemory {
      String stringCalculatedByWidgetA;
}

Then make sure that WidgetB updates the value in the shared memory.

Upvotes: 0

Related Questions