Flutter notes : Inherited Widget

Nipuna Cooray PhD
2 min readJan 22, 2021
Code
Photo by Caspar Camille Rubin on Unsplash

I’ve started learning Flutter recently and this is my takeaway of inherited widgets.

Since everything is a widget in Flutter, we build the app using composition, i.e we join widgets together to create a series of widgets. We call this the widget tree. So if we need to pass down some data through the tree, we have to pass this data, traversing the tree going through all the children even though some of them might not need this data.

This is where inherited widget (AuthProvider in this example) comes handy. We can create an inherited widget which contains the class (AuthBase in this case) that we need to provide, and give it to a parent in the widget tree, and all the children under that parent, will have access to the class within the inherited widget. And we can create a child property in this class which we can use when injecting this in the widget tree. Also, we can create a static method in this class which children can use when requesting the “auth” property from the inherited widget.

import 'package:flutter/material.dart';
import 'package:safe_app/services/auth_service.dart';

class AuthProvider extends InheritedWidget {
AuthProvider({@required this.auth, @required this.child});

final AuthBase auth;
final Widget child;

@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) => false;

static AuthBase of(BuildContext context) {
AuthProvider provider =
context.dependOnInheritedWidgetOfExactType<AuthProvider>();
return provider.auth;
}
}

Below is how we inject this AuthProvider i.e the inherited widget to the widget tree.

class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return AuthProvider(
auth: Auth(),
child: MaterialApp(
title: 'Safe App',
theme: ThemeData(
primarySwatch: Colors.indigo,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: LandingPage(),
routes: {
WelcomeScreen.id: (context) => WelcomeScreen(),
LoginScreen.id: (context) => LoginScreen(),
RegisterScreen.id: (context) => RegisterScreen(),
HomeScreen.id: (context) => HomeScreen(),
ModuleHomeScreen.id: (context) => ModuleHomeScreen(),
},
),
);
}
}

Once injected, children widgets can use the static method to request the injected auth property.

final auth = AuthProvider.of(context);

Thats it. This is also the base of the famous ‘Provider’ package in Flutter.

I am writing this as a note for myself, so it may not be 100% clear. I’ll try to update this if necessary and when I learn more about inherited widgets.

--

--