iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🏫

[FlutterGakkai] Will the Arrival of Macros Lead to a Resurgence of InheritedWidget?

に公開

The 6th FlutterGakkai was held recently, and I had the opportunity to give a presentation titled "Will InheritedWidget make a comeback with the arrival of Macros?"

The presentation is available on YouTube, so please check it out if you are interested in the video.

https://www.youtube.com/live/Cw-MnYAjR3o?si=rjcrirbkK2a1NZo8&t=5876

In this presentation, I incorporated several new attempts for myself, such as an introductory skit and live coding. Although there were various technical difficulties, I'm glad that the offline participants seemed to enjoy it quite a bit.

On the other hand, for online participants, there were parts where the message might not have come through—such as the microphone audio being missing during live coding or the video freezing—so I would like to summarize the main points in this article.

Also, since I omitted several points due to time constraints, I would like to supplement them in this article as well.

What is InheritedWidget?

InheritedWidget is a standard Flutter widget responsible for holding the "state" of an application.

While StatefulWidget, which also manages state, handles state confined within that specific widget, InheritedWidget is responsible for managing app state, which can be shared across the entire application.

Furthermore, it is equipped with a mechanism for O(1) access so that performance does not drop no matter how deep the widget tree becomes, and a mechanism to rebuild widgets that use the value when the held state changes. It can be said that it is an indispensable widget for Flutter, which builds UIs declaratively.

Standard widgets such as MediaQuery, DefaultTextStyle, and Theme use this InheritedWidget internally, and as a "user," it's a widget you're bound to encounter when developing apps.

The InheritedWidget Boilerplate Problem

However, as you know, there are not many opportunities to implement classes inheriting from InheritedWidget yourself in normal app development. Instead, most people probably use state management packages like Riverpod or BLoC.

One reason for this is that there is a lot of "routine" code required to use InheritedWidget (the boilerplate problem).

As an experiment, let's try creating an InheritedWidget called ClockTheme that holds ClockThemeData to be applied to a custom widget called TinyClock.

1. Define a class extending InheritedWidget

When creating a custom InheritedWidget, you define a widget class that extends InheritedWidget.

class ClockTheme extends InheritedWidget {   
}

An InheritedWidget needs to pass a child to the parent class's constructor.

Also, since InheritedWidget itself does not have the functionality to generate or change state within the class, we should implement it so that it receives the ClockThemeData to be held as a constructor argument and stores it in a field.

class ClockTheme extends InheritedWidget {
  const ClockTheme({
    super.key,
    required this.data,
    required super.child,
  });

  final ClockThemeData data;
}

2. Override necessary methods

Subclasses of InheritedWidget must implement the updateShouldNotify method by overriding it.

This method controls whether to rebuild descendant widgets that use the InheritedWidget when the InheritedWidget itself is rebuilt.

Typically, it is implemented to return true if the held state (in this case, data) has changed.

class ClockTheme extends InheritedWidget {
  const ClockTheme({
    ...
  });

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return data != (oldWidget as ClockTheme).data;
  }
}

3. Provide the .of() method

In order for descendants to access the InheritedWidget, they need to call a method on context called dependOnInheritedWidgetOfExactType<T>().

However, calling this directly is often avoided because the method name is long and it can be mentally taxing for the caller to figure out what to specify for <T>. Therefore, it is common practice to provide a .of() method on the InheritedWidget side that implements the appropriate way to call it.

class ClockTheme extends InheritedWidget {
  const ClockTheme({
    ...
  });

  static ClockThemeData of(BuildContext context) {
    final theme =
        context.dependOnInheritedWidgetOfExactType<ClockColorTheme>();
    return theme?.data ?? ClockThemeData();
  }

  ...
}

After writing several things, it is now complete. Let me show the full code of the finished version again.

class ClockTheme extends InheritedWidget {
  const ClockTheme({
    super.key,
    required this.data,
    required super.child,
  });

  final ClockThemeData data;

  static ClockThemeData of(BuildContext context) {
    final theme =
        context.dependOnInheritedWidgetOfExactType<ClockTheme>();
    return theme?.data ?? ClockThemeData();
  }

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return data != (oldWidget as ClockTheme).data;
  }
}

4. Usage

Since InheritedWidget is a widget referenced by descendants, it must be placed higher in the tree than the widgets that want to refer to it. For now, as an extreme example, let's place it as the parent of MyApp(), which is passed to runApp().

runApp(
  ClockTheme(
    data: ClockThemeData(),
    child: MyApp(),
  ),
);

By doing this, it becomes accessible from descendant widgets (in this case, TinyClock) as follows:

@override
Widget build(BuildContext context) {
  final theme = ClockTheme.of(context); 
}

This looks quite familiar, doesn't it?

5. Creating a mechanism to update state

Now, is this the end? Not quite. What we have done so far is just creating a widget that "holds state." In other words, we still cannot "update the state."

Since InheritedWidget is a widget, it is immutable, and unlike StatelessWidget, it doesn't have a build() method to construct a UI. Therefore, we need another widget to receive a new ClockThemeData and trigger a rebuild.

We will implement this role using a StatefulWidget. Let's name it ClockThemeMaintainer.

class ClockThemeMaintainer extends StatefulWidget {
  const ClockThemeMaintainer({super.key, required this.child});

  final Widget child;

  @override
  State<ClockThemeMaintainer> createState() => ClockThemeMaintainerState();
}

class ClockThemeMaintainerState extends State<ClockThemeMaintainer> {

  var _theme = ClockThemeData();

  @override
  Widget build(BuildContext context) {
    return ClockTheme(
      data: _theme,
      child: widget.child,
    );
  }
}

We implemented a build() method that places the previously created ClockTheme as a child widget within a typical StatefulWidget template. The ClockThemeData passed as data is held in a mutable form within a field of the State class.

Next, let's provide a method to update this _theme field.

class ClockThemeMaintainer extends StatefulWidget {
  ...
}

class ClockThemeMaintainerState extends State<ClockThemeMaintainer> {
  var _theme = ClockThemeData();

  void update(ClockThemeData data) {
    setState(() {
      _theme = data;
    });
  }

  @override
  Widget build(BuildContext context) {
    ...
  }
}

It is a simple structure that just assigns the ClockThemeData received as an argument to _theme and calls setState().

6. Accessing the StatefulWidget from descendants

Now, the problem arises: how do we call this update method?

This StatefulWidget is purely for managing state updates at the top of the widget tree, while the role of constructing the UI, such as a "change theme button," belongs to other descendant widgets.

A method called findAncestorStateOfType<T>() is available in context to access State objects like ClockThemeMaintainerState. However, since it is mentally taxing for the user to call it directly, it is common to provide an .of() method for easy access.

class ClockThemeMaintainer extends StatefulWidget {
  ...

  static ClockThemeMaintainerState of(BuildContext context) {
    return context.findAncestorStateOfType<ClockThemeMaintainerState>()!;
  }

}

class ClockThemeMaintainerState extends State<ClockThemeMaintainer> {
  ...
}

Unlike the previous InheritedWidget, findAncestorStateOfType<T>() for retrieving State has a time complexity of O(n), so the speed decreases as the widget tree gets deeper.

In other words, it is inappropriate for use within a build() method and is intended for cases where it is needed only once at a specific timing, such as when a button is tapped.

So, now that we have implemented the StatefulWidget for updates, let's place it at the root of the widget tree. Change the parent of MyApp from ClockTheme to ClockThemeMaintainer.

runApp(
  ClockThemeMaintainer(
    child: MyApp(),
  ),
);

Once this is done, you can implement the code to update the color of TinyClock when a button in the UI is tapped as follows:

onTap: () {
  ClockThemeMaintainer.of(context).update(selectedData);
}

This, too, has become a form you might have seen somewhere. Navigator.of(context).push(), etc., are built on the same mechanism.


And with that, we are finally able to "update the state of an InheritedWidget located at a distant position in the widget tree."

While there is certainly a benefit to being able to fine-tune the code once you understand the mechanism, basically, it is a task of simply writing "boilerplate" code. This can be said to be one of the reasons why using InheritedWidget directly is often avoided.

What are Macros?

In a nutshell, macros are "Dart code that generates Dart code."

A similar mechanism is build_runner, which has the following characteristics:

  • Requires explicit command execution.
  • Generated code is saved as files.

In contrast, macros are regenerated every time you type a character, and the generated code is not saved as a file.

"Mechanically generating code" means we can expect improved development efficiency by automating the writing of "boilerplate code that had to be written mechanically."

The Current State of Macros

However, since macros are still an experimental feature, it cannot be said that they are comfortable to use yet. You have to specify Flutter's master channel, add the --enable-experiment=macros option when running, and deal with unorganized documentation or unimplemented parts.

If you want to try implementing macros now, you'll probably go through a process of trial and error: read the official documentation to set up your environment, look at implementation samples to get a feel for the implementation, and read the feature-specification to understand the underlying logic. [1]

If you want to "get your hands dirty" for now, although it's my own work and in English, I have published a step-by-step guide for macro development below. Please feel free to refer to it.

https://chooyan.hashnode.dev/series/flutter-macros

Trying Out Macros

[Promotion] Regarding this part, I will be demonstrating several examples of macro usage at the following online event on Monday, August 5th, starting at 12:00 PM JST. Please take a look if you're interested. (I will add the same content here at a later date.)

https://yumemi.connpass.com/event/325497

InheritedWidget x Macros

So, what happens when we use such macros to improve InheritedWidget?

Looking at the result, the long code from the beginning is improved as follows:

@Stateful()
@Inherited()
class ClockTheme {
}

Although the specific code may vary depending on the design of the macro class and the requirements, the amount of code can be expected to be reduced this much. [2]

With the reduction in code and no longer needing to be mindful of how to implement the somewhat complex .of(context) method, the usability seems likely to become quite good.

[2:1]

InheritedWidget and State Management Packages

So, when this is realized, will state management packages like Riverpod or BLoC become unnecessary?

Unfortunately, the answer is no.

While it is certainly possible to "reduce the minimal boilerplate of InheritedWidget," in actual app development, we often face challenges that cannot be solved by "minimal boilerplate" alone or challenges that are "unavoidable as long as it is an InheritedWidget."

For example, InheritedWidget cannot be simply "disposed." If you try to remove it from the widget tree to dispose of it, the depth of the widgets changes, causing the Elements and States of the entire subtree to be destroyed and recreated. Since this might make the UI look as if it "suddenly returned to its initial state," some measures like using a GlobalKey must be taken.

Generation and update processes for states involving Future or Stream also need to be properly managed while being mindful of the widget tree mechanism yourself.

Since state management is a difficult challenge where just being able to "hold" and "update" isn't enough, I don't think that just because InheritedWidget becomes a bit easier to use, it will completely replace existing state management packages.

However, it is likely to have the effect of "increasing options."

In very simple apps, it might be possible to manage state sufficiently by appropriately using InheritedWidget and StatefulWidget. There might also be an option to meet requirements with minimal dependencies by combining standalone packages like riverpod or bloc (which do not depend on Flutter) with InheritedWidget.

This will likely be considered based on what the requirements are, how much can be covered by ingenuity within the project, and at what point to rely on the features of a state management package.

Summary

So far, we have looked step-by-step at what InheritedWidget is, what macros are, and how development might change if InheritedWidget is improved using macros.

In conclusion, while the arrival of macros is unlikely to fundamentally change state management, I believe it could have enough of an impact to introduce patterns using InheritedWidget as a "new option."

Since macros themselves are still in experimental release, it's impossible to predict exactly what will be possible when they are actually released, but I think it's not a bad idea to try them out at this stage and start gathering ideas. [3]

脚注
  1. At least, that's how it is for me. ↩︎

  2. I haven't been able to verify the behavior yet due to issues with the macros themselves, so it stays at the level of "it looks like the same thing can be achieved with just this much code (code generation was successful)." ↩︎ ↩︎

  3. It's certainly difficult to handle, so I wouldn't recommend it lightly, but... ↩︎

GitHubで編集を提案

Discussion