Flutter detect when value passed to the statefull widget changes

Viewed 176

I have a statefull widget where am passing an integer to. 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. How can i detect when the value passed statefull widget has changed?

1 Answers

You can check the useEffect, which is based on the React hook useEffect.

Or you can hardcode it.

Create other integer: late int lastCalledInteger;

And check this in the build:

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

  return Container();
}
Related