Your Second Flutter App

Nov 30 2021 · Dart 2.13, Flutter 2.2.3, Visual Studio Code

Part 5: Meet Inherited Widgets

33. Create an Inherited Widget

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 32. Learn Flutter State Management Next episode: 34. Lift State Up

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

An InheritedWidget is useful for lifting state up because it can be accessed by any widget in the widget tree.

import 'package:flutter/material.dart';

class FilterStateContainer extends StatefulWidget {

}
final Widget child;

const FilterStateContainer({Key? key, required this.child}) : super(key: key);
  @override
  State<StatefulWidget> createState() => FilterState();
class FilterState extends State<FilterStateContainer> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
class FilterStateContainer extends StatefulWidget {
  ...
  static FilterState of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<_FilterInheritedWidget>()!
        .state;
  }
class FilterState extends State<FilterStateContainer> {
  int filterValue = Constants.allFilter;
  late SharedPreferences _prefs;
}
import '../constants.dart';

class FilterState extends State<FilterStateContainer> {
  ...
  @override
  void initState() {
    super.initState();

    _loadValue();
  }

  void _loadValue() {
    SharedPreferences.getInstance().then((value) {
      _prefs = value;
      setState(() {
        filterValue = _prefs.getInt(Constants.filterKey) as int;
      });
    });
  }
class FilterState extends State<FilterStateContainer> {
  ...
  void updateFilterValue(int value) {
    setState(() {
      _prefs.setInt(Constants.filterKey, value);
      filterValue = value;
    });
  }
class _FilterInheritedWidget extends InheritedWidget {
}
class _FilterInheritedWidget extends InheritedWidget {
  final FilterState state;

  const _FilterInheritedWidget({
    Key? key,
    required this.state,
    required Widget child,
  }) : super(key: key, child: child);
class _FilterInheritedWidget extends InheritedWidget {
  ...
  @override
  bool updateShouldNotify(_FilterInheritedWidget oldWidget) => true;
class FilterState extends State<FilterStateContainer> {
  ...
  @override
  Widget build(BuildContext context) {
    return _FilterInheritedWidget(
      state: this,
      child: widget.child,
    );
  }