Vishnu Prasad
Vishnu Prasad

Reputation: 63

Best way to pass data from a root to deeper child widget in Flutter

I am new to flutter. My flutter widget tree is getting deeper and deeper, I want to know which is the best method to pass data from a root to a widget which is much deeper from it. I'm currently passing it as a constructor from widget to widget. My current implementation is given below

Level1(data: data)
  Level2(data: data)
    Level3(data: data)
       Level4(data: data)

suppose my data is retrieved from DB in level1 widget and it is used in level4 widget. As we see, my current implementation is considerably messy. How this is generally done? what is the best practice?

Upvotes: 0

Views: 595

Answers (2)

towhid
towhid

Reputation: 3288

Inherited widget - If you want to avoid using any third party library..

More can be found here - https://medium.com/@mehmetf_71205/inheriting-widgets-b7ac56dbbeb1

and here https://www.youtube.com/watch?v=Zbm3hjPjQMk

class MyInheritedWidget extends InheritedWidget {
  final int accountId;
  final int scopeId;

  MyInheritedWidget(accountId, scopeId, child): super(child);
  
  @override
  bool updateShouldNotify(MyInheritedWidget old) =>
    accountId != old.accountId || scopeId != old.scopeId;
}

class MyPage extends StatelessWidget {
  final int accountId;
  final int scopeId;
  
  MyPage(this.accountId, this.scopeId);
  
  Widget build(BuildContext context) {
    return new MyInheritedWidget(
      accountId,
      scopeId,
      const MyWidget(),
     );
  }
}

class MyWidget extends StatelessWidget {

  const MyWidget();
  
  Widget build(BuildContext context) {
    // somewhere down the line
    const MyOtherWidget();
    ...
  }
}

class MyOtherWidget extends StatelessWidget {

  const MyOtherWidget();
  
  Widget build(BuildContext context) {
    final myInheritedWidget = MyInheritedWidget.of(context);
    print(myInheritedWidget.scopeId);
    print(myInheritedWidget.accountId);
    ...

Upvotes: 1

Alex
Alex

Reputation: 1957

You might like to use Provider. You can find more about it here.

Basically, you create provider of the data at the top-most level like:

class Level1 {
@override
  Widget build(BuildContext context) {
    Provider<Data>(
      create: (_) => Something(),
      child: Level2 (
         // stuff of level 2
      ),
    ),
  }
}

Something in this case bight be a change notifier.

You can then access it at a lower level with:

final provider = Provider.of<Something>(context);

Upvotes: 3

Related Questions