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
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 32. Learn Flutter State Management Next episode: 34. Lift State Up

This video Create an Inherited Widget was last updated on Nov 30 2021

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

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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,
    );
  }