0

How we can modify instance in child, created in parent widget and passed to child.

Do I have to use streams or call backs? Whats the easiest way to modify data on child while it should reflect on parents too.

1 Answers1

0

I think you want something like ValueNotifier and ValueListenableBuilder Widgets. Like you said, if you put the data in parents to ValueNotifier Widget with its type. Then wrap everything that needs to change when data changes in ValueListenableBuilder Widget.

More Info:

Look at this example:

  ValueNotifier<int> valueListener = ValueNotifier<int>(0);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ValueListenableBuilder(
        valueListenable: valueListener,
        builder: (BuildContext context, int value, Widget? child) {
          return Column(
            mainAxisAlignment: (value%2) == 0 ? MainAxisAlignment.start : MainAxisAlignment.end,
            children: [
              TextButton(
                onPressed: () => valueListener.value++,
                child: Center(
                  child: Text("$value"),
                ),
              ),
            ],
          );
        },
      ),
    }
Hazar Belge
  • 1,009
  • 4
  • 20
  • Lets assume we have parent with data field User, and you to access down the hierarchy in 15th child , using notifier will be a mess. I found a way of using Inherited widget. Trying that. Will update here – Shariq Bin Rashid Aug 29 '21 at 18:26