Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Mutate the Inherited Widget

This video was last updated on Sep 22 2022

While the Inherited Widget is able to manage state it requires some work to manage mutable state. Learn how to combine a Stateful Widget with an Inherited Widget to create mutable state.

Contributors

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 raywenderlich.com Professional subscription.

In the last episode, you implemented an inherited widget. You saw how it easy it was to access the widget in the widget tree and read from it. But unfortunately, you can’t change a value. Inherited widget’s are immutable. Mind you, can access objects in an inherited that can mutate their own internal state, but you can’t change that object.

class PillarStatefulWidget extends StatefulWidget {
  const PillarStatefulWidget(
      {required this.pillarData, required this.child, Key? key})
      : super(key: key);

  final Widget child;
  final Pillar pillarData;
get articleCount => widget.pillarData.articleCount;
get imageName => widget.pillarData.type.imageName;
void increaseArticleCount({ int by = 1 }) {
    setState(() {
        widget.pillarData.increaseArticleCount(by: by);
    });
}
final PillarState state;
final int articleCount;
  const PillarInheritedWidget(
      {required this.articleCount,
      required this.state,
      super.key,
      required super.child});
static PillarState of(BuildContext context) {
    final PillarInheritedWidget? result =
        context.dependOnInheritedWidgetOfExactType<PillarInheritedWidget>();
    assert(result != null, 'No PillarWidget found in context');
    return result!.state;
}
  bool updateShouldNotify(PillarInheritedWidget oldWidget) {
    return !(oldWidget.articleCount == articleCount);
  }
Widget build(BuildContext context) {
    return PillarInheritedWidget(
        articleCount: widget.pillarData.articleCount,
        state: this,
        child: widget.child,
    );
}
body: PillarStatefulWidget(
    pillarData: pillarData,
    child: const TutorialsPage(),
),
final pillar = PillarInheritedWidget.of(context);
'Total Tutorials: ${pillar.articleCount}',
final pillar = PillarInheritedWidget.of(context);
InkWell(
    onTap: () {
    pillar.increaseArticleCount();
    },
    child: Image.asset('assets/images/${pillar.imageName}',
        width: 110, height: 110),
),
CircleAvatar(
    backgroundColor: Colors.blue,
    child: Text(pillar.articleCount.toString()),

Reviews

Comments