Skip to content

Instantly share code, notes, and snippets.

@lyuz1n
Last active April 20, 2022 00:11
Show Gist options
  • Select an option

  • Save lyuz1n/ceb99375a2ee51b2d4fca78d3f2a622a to your computer and use it in GitHub Desktop.

Select an option

Save lyuz1n/ceb99375a2ee51b2d4fca78d3f2a622a to your computer and use it in GitHub Desktop.
Simple State Manager & Dependence Injection
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);
}
@Borep
Copy link

Borep commented Apr 20, 2022

gid:XEGjd9hs5X8uNmxrni4XEY

@Borep
Copy link

Borep commented Apr 20, 2022

gid:XEGjd9hs5X8uNmxrni4XEY

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment