简体   繁体   中英

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

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.

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.

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