Sobes.tech
Junior — Middle

Can you give an example of using InheritedWidget in Flutter?

sobes.tech AI

Answer from AI

InheritedWidget in Flutter is used to pass data down the widget tree without the need to explicitly pass it through the constructors of each child widget.

Example of usage: creating a theme or settings that should be accessible to many widgets in the app.

A simple example is passing a string with a color setting:

class MySettings extends InheritedWidget {
  final Color color;

  const MySettings({
    Key? key,
    required this.color,
    required Widget child,
  }) : super(key: key, child: child);

  static MySettings? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MySettings>();
  }

  @override
  bool updateShouldNotify(MySettings oldWidget) => color != oldWidget.color;
}

// Usage:

class ColoredText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final settings = MySettings.of(context);
    return Text(
      'Hello, Flutter!',
      style: TextStyle(color: settings?.color ?? Colors.black),
    );
  }
}

Thus, all widgets inside MySettings can access the color without manually passing parameters.

Can you give an example of using InheritedWidget in… - sobes.tech