簡體   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