inherited_settings_state.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import 'package:flutter/widgets.dart';
  2. /// StatefulWidget that wraps InheritedSettingsState
  3. class SettingsStateContainer extends StatefulWidget {
  4. const SettingsStateContainer({
  5. Key? key,
  6. required this.child,
  7. }) : super(key: key);
  8. final Widget child;
  9. @override
  10. State<SettingsStateContainer> createState() => _SettingsState();
  11. }
  12. class _SettingsState extends State<SettingsStateContainer> {
  13. int _expandedSectionCount = 0;
  14. void increment() {
  15. setState(() {
  16. _expandedSectionCount += 1;
  17. });
  18. }
  19. void decrement() {
  20. setState(() {
  21. _expandedSectionCount -= 1;
  22. });
  23. }
  24. @override
  25. Widget build(BuildContext context) {
  26. return InheritedSettingsState(
  27. expandedSectionCount: _expandedSectionCount,
  28. increment: increment,
  29. decrement: decrement,
  30. child: widget.child,
  31. );
  32. }
  33. }
  34. /// Keep track of the number of expanded sections in an entire menu tree.
  35. ///
  36. /// Since this is an InheritedWidget, subsections can obtain it from the context
  37. /// and use the current expansion state to style themselves differently if
  38. /// needed.
  39. ///
  40. /// Example usage:
  41. ///
  42. /// InheritedSettingsState.of(context).increment()
  43. ///
  44. class InheritedSettingsState extends InheritedWidget {
  45. final int expandedSectionCount;
  46. final void Function() increment;
  47. final void Function() decrement;
  48. const InheritedSettingsState({
  49. Key? key,
  50. required this.expandedSectionCount,
  51. required this.increment,
  52. required this.decrement,
  53. required Widget child,
  54. }) : super(key: key, child: child);
  55. bool get isAnySectionExpanded => expandedSectionCount > 0;
  56. static InheritedSettingsState of(BuildContext context) =>
  57. context.dependOnInheritedWidgetOfExactType<InheritedSettingsState>()!;
  58. static InheritedSettingsState? maybeOf(BuildContext context) =>
  59. context.dependOnInheritedWidgetOfExactType<InheritedSettingsState>();
  60. @override
  61. bool updateShouldNotify(covariant InheritedSettingsState oldWidget) {
  62. return isAnySectionExpanded != oldWidget.isAnySectionExpanded;
  63. }
  64. }