Last active
April 20, 2022 00:11
-
-
Save lyuz1n/ceb99375a2ee51b2d4fca78d3f2a622a to your computer and use it in GitHub Desktop.
Simple State Manager & Dependence Injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/material.dart'; | |
| abstract class Homura { | |
| static final Map<Type, ChangeNotifier> _controllers = {}; | |
| static ChangeNotifier put(ChangeNotifier controller, {bool replaceOld = false}) { | |
| final Type type = controller.runtimeType; | |
| bool oldRemoved = false; | |
| if (replaceOld && _controllers[type] != null) { | |
| oldRemoved = _controllers.remove(type) != null; | |
| } | |
| if (_controllers[type] == null) { | |
| _controllers[type] = controller; | |
| debugPrint('[Homura]: $type ${oldRemoved ? 'replaced' : 'initialized'}.'); | |
| } | |
| return controller; | |
| } | |
| static void delete<T extends ChangeNotifier>() { | |
| if (_controllers[T] != null && _controllers.remove(T) != null) { | |
| debugPrint('[Homura]: $T deleted.'); | |
| } | |
| } | |
| static T get<T extends ChangeNotifier>() { | |
| if (_controllers[T] != null) return _controllers[T] as T; | |
| throw '[Homura]: Cannot find $T! Needs to initialize with "Homura.put($T());"'; | |
| } | |
| } | |
| abstract class HomuraController extends ChangeNotifier { | |
| void update() => notifyListeners(); | |
| } | |
| abstract class HomuraView<T extends ChangeNotifier> extends StatelessWidget { | |
| const HomuraView({Key? key}) : super(key: key); | |
| T get controller => Homura.get(); | |
| // ignore: non_constant_identifier_names | |
| Widget HBuilder(Widget Function() builder) { | |
| return AnimatedBuilder( | |
| animation: controller, | |
| builder: (context, child) => builder.call(), | |
| ); | |
| } | |
| } | |
| class HomuraBuilder<T extends ChangeNotifier> extends HomuraView<T> { | |
| const HomuraBuilder({Key? key, required this.builder}) : super(key: key); | |
| final Widget Function() builder; | |
| @override | |
| Widget build(BuildContext context) => HBuilder(builder); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gid:XEGjd9hs5X8uNmxrni4XEY