繁体   English   中英

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

[英]Flutter- Passing Data between Custom Widgets inside column

我坚持使用WidgetA()计算字符串,但我想将此字符串传递给WidgetB() - 如何将更新的数据传递给WidgetB

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

  ],
);

Widget A 是一个costum Class Stateful Widget

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

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

创建一个共享内存,例如一个类,并将值保存到一个类变量中。

class SharedMemory {
      String stringCalculatedByWidgetA;
}

然后确保 WidgetB 更新共享内存中的值。

暂无
暂无

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

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