flutter_inject 1.0.3 flutter_inject: ^1.0.3 copied to clipboard
A simple dependency injection widget based on standard Flutter's InheritedWidget
flutter_inject_example #
The classic counter example to show how it's easy to use the flutter_inject package.
main.dart #
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inject/flutter_inject.dart';
void main() => runApp(
const MaterialApp(
title: 'Counter example with the flutter_inject package',
home: CounterView(),
),
);
class CounterView extends StatelessWidget {
const CounterView({super.key});
@override
Widget build(BuildContext context) {
return Inject<CounterLogic>(
factory: (context) => CounterLogic(),
builder: (context) {
final logic = Dependency.get<CounterLogic>(context);
return Scaffold(
appBar: AppBar(title: const Text('Counter demo')),
body: Center(
child: StreamBuilder(
initialData: logic.state,
stream: logic.controller.stream,
builder: (context, snapshot) => Text('Counter: ${snapshot.data}'),
),
),
floatingActionButton: FloatingActionButton(
onPressed: logic.increment,
child: const Icon(Icons.add),
),
);
},
);
}
}
class CounterLogic with Disposable {
int state = 0;
final controller = StreamController<int>();
void increment() => controller.add(++state);
@override
void dispose() => controller.close();
}