首页 > 解决方案 > Flutter-在列内的自定义小部件之间传递数据

问题描述

我被一个WidgetA()计算字符串的方法卡住了,但我想将此字符串传递给WidgetB()- 如何将更新的数据传递给WidgetB

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

  ],
);

Widget A 是一个服装类 Stateful Widget

标签: flutterdart

解决方案


对我来说,最明显的方法是将数据存储在父窗口小部件的状态中。然后,您可以提供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 和 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');
  }
}

根据值及其更新频率,也可以使用某种存储方式,例如值的共享首选项


推荐阅读