简体   繁体   English

Flutter 检测传递给有状态小部件的值何时发生变化

[英]Flutter detect when value passed to the statefull widget changes

I have a statefull widget where am passing an integer to.我有一个有状态的小部件,我将 integer 传递给它。 I would like to execute a method when the value passed to the widget changes我想在传递给小部件的值发生变化时执行一个方法

class Test extends StatefulWidget {
 final String item;
 const Test({
  Key? key,
  required this.item,
 }) : super(key: key);

@override
_TestState createState() => _TestState();
}

class _TestState extends State<Test> {
 List<String> hh = [];

 @override
 void initState() {
  super.initState();
  print("init state value is  ${widget.item}");
 }

 @override
 Widget build(BuildContext context) {
  return Container();
 }

 void getDataItems() {
  print("value passed is ${widget.item}");

  setState(() {
    hh = [widget.item];
  });
 }
}

So on the above i would like to detect when the value of string item passed to the widget changes and call the method getDataItems which will later update the list hh.所以在上面我想检测传递给小部件的字符串项的值何时更改并调用方法getDataItems稍后将更新列表 hh。 How can i detect when the value passed statefull widget has changed?我如何检测传递给 statefull 小部件的值何时发生变化?

You can check the useEffect , which is based on the React hook useEffect.您可以检查useEffect ,它基于 React hook useEffect。

Or you can hardcode it.或者您可以对其进行硬编码。

Create other integer: late int lastCalledInteger;创建其他 integer: late int lastCalledInteger;

And check this in the build:并在构建中检查:

@override
Widget build(BuildContext context) {
  if(lastCalledInteger != integer) {
    getDataItems();
    lastCalledInteger = integer;
  }

  return Container();
}

You can simply override didUpdateWidget on State to be informed of every change of passed in arguments. If you have multiple arguments you of course need to change what changed.您可以简单地重写didUpdateWidget上的State ,以了解 arguments 中传递的每项更改。如果您有多个 arguments,您当然需要更改更改的内容。 For this didUpdateWidget provides you with the oldWidget as only parameter.为此, didUpdateWidget为您提供了oldWidget作为唯一参数。

From the documentation:从文档中:

Called whenever the widget configuration changes.每当小部件配置更改时调用。

[...] [...]

Override this method to respond when the widget changes (eg, to start implicit animations).覆盖此方法以在小部件更改时做出响应(例如,启动隐式动画)。

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

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