The Wayback Machine - https://web.archive.org/web/20240620194526/https://www.geeksforgeeks.org/flutter-inherited-widget/
Open In App

Flutter – Inherited Widget

Last Updated : 30 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

If you are a flutter developer then you know how easy is to create Flutter UI. But when you have lots of widgets in your app and you want to pass data from one widget to another widget, this will be a pain for many developers,s especially for the newbie, this will be really hard for them to pass the data from a widget of widget tree to bottom widget. And if know about widgets there are generally two types of widgets Stateless and stateful widgets. But there is another type of widget called InheritedWidget.

 

InheritedWidget

The inherited widget provides us with a convenient way to pass data between widgets. While developing an app you will need some data from your parent’s widgets or grant parent widgets or maybe beyond that. So if your app is small you can pass your data using the constructor of the widget class, but for a larger app, this is not an easy task. Unknowingly we have used inherited widgets in many places while developing the flutter app.Theme.of(context), MediQuery.of(context), and Navigator.of(context)  (if you check the codes of Navigation you will find that).

Dart




const InheritedWidget({
Key? key, required Widget child
})
: super(key: key, child: child);


The first parameter is the key, a key is an identifier for widgets, and elements in Flutter. A new widget will only be used to update an existing widget if its key is the same as the key of the current widget associated with the element. The child parameter is of type Widget so we can pass any widget as a parameter as a child widget. Let’s create a simple example,

Dart




import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyScreen(),
    );
  }
}
 
class MyInheritedWidget extends InheritedWidget {
  const MyInheritedWidget({Key? key,required this.child,required this.message}) : super(key: key, child: child);
 
  final Widget child;
   
  // message of our inherited widget class
  final String message;
 
  static MyInheritedWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>()!;
  }
 
  @override
  bool updateShouldNotify(MyInheritedWidget oldWidget) {
    return oldWidget.message != message;
  }
}
 
class MyScreen extends StatelessWidget {
  const MyScreen({Key? key}) : super(key: key);
 
    @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("GFG"),
        backgroundColor: Colors.green,
      ),
      body: MyInheritedWidget(
        // passing the message as string
        message:"Hey GEEKS",
        child: Builder(
          builder: (BuildContext innerContext) {
     
            return Center(
                        child: Text(
                     // using the message of our inherited widget using of()
                     MyInheritedWidget.of(innerContext).message,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                )
              );
          },
        ),
      ),
    );
  }
}


Output:

Output

 

The inherited widget class is immutable. Here we have created a String variable called message and it’s declared as final so we can not modify it in the future. We override one method called updateShouldNotify which has a parameter old widget, this method is used to notify the widget when we rebuild the widget,  For example, if the data held by this widget is the same as the data held by the old widget, then we do not need to rebuild the widgets and we don’t need to notify the widget. But the important part is the static of(), is it mandatory to define it in our inherited widget? The answer is NO. But this is a convention that we follow, you can directly call context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>() and use that.

Few developers define the inherited widget as private and implement it in another class, there is no stand way of defining an inherited widget but if you look at the Theme.of(context) codes you will see it used a private InheritedWidget class.

Note: See we are using Builder() and innerContext to access the message of the inherited widget, if you use context then it won’t work. Flutter says When we use the method, the context must be a descendant of InheritedWidget, which means the context must be below the inheridWidget in the tree.

The above example is a simple example, Let’s do a complicated example,

Dart




import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyNavigation(),
    );
  }
}
 
// route function for  Routing of pages
Route generatePage(child) {
  return MaterialPageRoute(builder: (context) => child);
}
 
class MyNavigation extends StatelessWidget {
  const MyNavigation({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return MyInheritedWidget(
      // message as string for our inherited widget
      message: 'Hey, Geekss',
      child: Navigator(
        onGenerateRoute: (settings) {
          switch (settings.name) {
            case 'screen1':
              // Route for firs screen
              return generatePage(const FirstScreen());
            case 'screen2':
              // Route for second screen
              return generatePage(const SecondScreen());
           
          }
        },
        // our first screen in app
        initialRoute: 'screen1',
      ),
    );
  }
}
 
class MyInheritedWidget extends InheritedWidget {
  const MyInheritedWidget({Key? key,required this.child,required this.message}) : super(key: key, child: child);
 
  @override
  final Widget child;
   
  // message variable for
  // our inherited widget
  final String message;
 
  static MyInheritedWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>()!;
  }
 
  @override
  bool updateShouldNotify(MyInheritedWidget oldWidget) {
    return true;
  }
}
 
class FirstScreen extends StatelessWidget {
  const FirstScreen({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Geeks For Geeks'),
        backgroundColor: Colors.green,
      ),
   
      body: Center(
        child: ElevatedButton(
          // showing message variable of our
          // inherotedd widget class using of()
          child: Text(MyInheritedWidget.of(context).message),
          onPressed: () {
            Navigator.of(context)
                   // navigate to second screen
                .push(MaterialPageRoute(builder: (_) => SecondScreen()));
          },
        ),
      ),
    );
  }
}
 
class SecondScreen extends StatelessWidget {
  const SecondScreen({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Geeks For Geeks'),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Text(MyInheritedWidget.of(context).message + "\n This is second screen",style: const TextStyle(fontWeight: FontWeight.bold),),
        // showing message variable of our
        // inherotedd widget class using of()
      )
    );
  }
}


Final Output:

Explanation:

In the above example, we just create two screens and use navigation, If you check the code properly you see that we create a navigation widget as a child of MyInheritedWidget.  We use the message variable of MyInheritedWidget on both screens. If we don’t create a Navigation widget as a child of MyInheritedWidget, then we can not access the message variable of MyInheritedWidget. We can use InheritedWidget as a state management tool but the complexity will increase, so the flutter team recommends that for a complex and large app we should use some state management tool.



Similar Reads

Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Flutter - Card Widget
Card is a build-in widget in flutter which derives its design from Google's Material Design Library. The functionality of this widget on screen is, that it is a bland space or panel with round corners and a slight elevation on the lower side. It comes with many properties like color, shape, shadow color, etc which lets developers customize it the w
4 min read
Flutter - ColoredBox Class Widget
A Colored Box is a container that fills it with color according to its child or A widget that paints its area with a specified Color and then draws its child on top of that color. A sample image is given below to get an idea about what we are going to do in this article. How to use it? You can simple use this widget anywhere in your project as you
3 min read
How to Get the Height of a Widget in Flutter?
To get the height of a widget in Flutter, you can use the LayoutBuilder widget to obtain the constraints of the parent container and then get the height from those constraints. How to use it? You can simply use this widget anywhere in your project as you needed that. LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { doubl
3 min read
Difference Between Stateless and Stateful Widget in Flutter
As we all know the flutter app consists of widgets only, these are broadly classified into two types: Stateless WidgetStateful WidgetState: Before knowing the difference between the stateless and stateful widget we should take a look at the definition of State of a widget. The State is information that can read synchronously when the widget is buil
3 min read
Flutter - Wrap Widget
Wrap widget aligns the widgets in a horizontal and vertical manner. Generally, we use Rows and Columns to do that but if we have some widgets which are not able to fit in the Row/Column then it will give us Overflow Message ( for ex: Right Overflowed by 570 pixels). Constructor of Wrap class:Wrap({Key key, Axis direction, WrapAlignment alignment, d
3 min read
Raised Button widget in Flutter
RaisedButton is the material design button based on a Material widget that elevates when pressed upon in flutter. It is one of the most widely used buttons in the flutter library. Let's understand this button with the help of an example. Disclaimer: As of May 2021 the RaisedButton class in flutter is deprecated. ElevatedButton class should be used
5 min read
OffStage Widget in Flutter
Flutter provides an inbuilt widget called “Offstage”, which is been used to hide or show any widget programmatically depending on user action/event. Offstage Widget is a widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit-testing, and without taking any room in the paren
4 min read
NotificationListener Widget in Flutter
In Flutter, every Scrollable sends Notifications that contain information about the current scroll state. So to catch these notifications we use NotificationListener Widget. NotificationListener Widget will listen for Notifications bubbling up the tree. In this, article we will learn about NotificationListener Widget Default Constructor:Notificatio
4 min read
endDrawer Widget in Flutter
The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default op
2 min read
Article Tags :