Pass a callback from the parent widget all the way down the widget tree to a descendant widget

Switching tabs

You have two options to implement switching to the Recipes tab:

  1. Standard callback: Pass a callback from the parent widget all the way down the widget tree to a descendant widget. When ready, it fires the callback at each level up the tree and calls setState() to rebuild the Home widget’s subtree.

Give me the example of the code, please :slight_smile:

Hi @eryawanir ,
Passing a callback might be best used when passing data from a child widget to a parent widget. Using callbacks in multiple levels of a widget tree might be a little bit tedious. Maybe @jomoka can help us on that.
But i’ll give you a simple example below:
Let’s say we have two widgets,
a child widget that looks like the one below:
On this widget, we have defined a callback final Function(int) onCountChanged;
There is a button, when a user clicks the button, onCounntChanged is called:

a parent widget that looks like the one below:
and a child widget that looks like the one below:

When a the elevated button is clicked, the change value is passed from the Count child widget to the CounterPage parent widget. Then, the addition between the val and count is performed and count is updated.

1 Like

@sheldoni thanks looks right!

Yea the down side to callbacks is if you have a deep tree of widgets you will couple every single widget with one another.

The best would be to use an inherited widget, or provider package to pass state up and down the widget tree.

1 Like

before learning flutter, I learned DOM javascript, it’s very difficult for me to adapt to flutter

flutter and DOM javascript are completely different

Thank you

can we use DOM selector inside Flutter? hahahahahaha

:thinking: hmmmmmmm :smiley: i’m not sure about that. I do know Flutter has two different types of rendering when deployed for Web.

I believe you can also use querySelector in flutter:
https://api.flutter.dev/flutter/dart-html/querySelector.html

You can check out:

  • HTML Renderer
  • CanvasKit Renderer