-1

In shorter word, my question is how to call child's initState() again on parent's setState().

I need to reuse a widget class for multiple instances. I need the widgets to appear in turn like below where I can use setState() to switch between them.

bool showthefirstone = true;

@override
Widget build(BuildContext context) {
  ...
  TheWidget it = showthefirstone ? TheWidget(...) : TheWidget(..);
  ...
}

The later one's initState() is not called. No problem showing them both together along at the same time. The issue only occurs upon setState().

For those who don't understand, this trigger the change

setState((){showthefirstone = !showthefirstone})
stackunderflow
  • 1,492
  • 1
  • 23
  • 53
  • Where is the trigger to change your widgets? Is a button, data response... – Rodrigo Rivas Sep 12 '22 at 20:23
  • I don't understand correctly, what condition do you want to call setState? Whenever a condition is met? If so, use didUpdateWidget and check the current widget object against the previous one to see what has changed. – Chance Sep 12 '22 at 20:24
  • @Chance the setState change the boolean value. i made my question simplest – stackunderflow Sep 12 '22 at 20:25
  • The answer is there is no way to call initState for state already assembled. For that there is didUpdateWidget, it is a lifecycle method that is called whenever the constructor receives a new value, so the widget object will change and you can call setState from inside him. – Chance Sep 12 '22 at 20:28
  • @Chance ok. so how to use same widget class multiple times at different time without call setstate from the widget class itself? – stackunderflow Sep 12 '22 at 20:30
  • Okay, does setState come from inside TheWidget widget? I'm having a hard time understanding how your widget changes state. – Chance Sep 12 '22 at 20:32
  • @Chance yes sure. i just want to reuse same widget class and rebuild the widget without need to define that same class in two different files – stackunderflow Sep 12 '22 at 20:36
  • @Chance i had a workaround. i just need a proper solution if any before go for it – stackunderflow Sep 12 '22 at 20:38
  • Same answer with different question https://stackoverflow.com/questions/69034391/force-rebuild-of-a-stateful-child-widget-in-flutter – stackunderflow Sep 12 '22 at 21:52

1 Answers1

0

It's the same answer with different question. My question is more generic. At least works for my case.

https://stackoverflow.com/a/70789848/1297048

stackunderflow
  • 1,492
  • 1
  • 23
  • 53