简体   繁体   English

Flutter-在列内的自定义小部件之间传递数据

[英]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 ?我坚持使用WidgetA()计算字符串,但我想将此字符串传递给WidgetB() - 如何将更新的数据传递给WidgetB

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

  ],
);

Widget A is a costum Class Stateful Widget Widget 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:然后,您可以为WidgetA提供回调以设置此状态,并为WidgetB提供以下值:

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: WidgetA 和 WidgetB 可能如下所示:

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.然后确保 WidgetB 更新共享内存中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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