Skip to content

Instantly share code, notes, and snippets.

@hawkkiller
Created September 21, 2024 12:51
Show Gist options
  • Select an option

  • Save hawkkiller/d5cf2087cee010e990e0ddc8b082b841 to your computer and use it in GitHub Desktop.

Select an option

Save hawkkiller/d5cf2087cee010e990e0ddc8b082b841 to your computer and use it in GitHub Desktop.
Scope used for lazy initialization
import 'package:flutter/material.dart';
class SettingsBloc {
void close() {}
}
/// {@template settings_scope}
/// SettingsScope widget.
/// {@endtemplate}
class SettingsScope extends StatefulWidget {
/// {@macro settings_scope}
const SettingsScope({
required this.child,
super.key, // ignore: unused_element
});
final Widget child;
/// You can also add listen parameter to listen to changes in the bloc.
static SettingsBloc of(BuildContext context) => context
.getInheritedWidgetOfExactType<_DependencyAInherited>()!
.settingsScopeState
.settingsBloc;
@override
State<SettingsScope> createState() => _SettingsScopeState();
}
/// State for widget SettingsScope.
class _SettingsScopeState extends State<SettingsScope> {
late final settingsBloc = SettingsBloc();
@override
void dispose() {
// Control the lifecycle
settingsBloc.close();
super.dispose();
}
/// If you want to notify about changes in the bloc, wrap it in bloc builder
@override
Widget build(BuildContext context) => _DependencyAInherited(
settingsScopeState: this,
child: widget.child,
);
}
/// {@template dependency_a_inherited}
/// _DependencyAInherited widget.
/// {@endtemplate}
class _DependencyAInherited extends InheritedWidget {
/// {@macro dependency_a_inherited}
const _DependencyAInherited({
required this.settingsScopeState,
required super.child,
super.key, // ignore: unused_element
});
final _SettingsScopeState settingsScopeState;
@override
bool updateShouldNotify(covariant _DependencyAInherited oldWidget) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment