Flutter get_it库,动态服务定位器
下面这个demo在两个页面都注入了CountService
来共享数据
// main.dart
import 'package:get_it/get_it.dart';
GetIt getIt = GetIt.instance;
void main() {
// 注意注册顺序
getIt
..registerSingleton<LoggerService>(LoggerService())
..registerSingleton<CountService>(CountService());
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
"/": (c) => HomePage(),
"/about": (c) => AboutPage(),
},
);
}
}
class HomePage extends StatelessWidget {
final count = getIt<CountService>(); // 注入
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
StreamBuilder(
stream: count.n$,
builder: (context, snapshot) {
return Text(snapshot.data.toString());
}),
FlatButton(
child: Text('To About'),
onPressed: () {
Navigator.of(context).pushNamed('/about');
},
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: count.add,
),
);
}
}
class AboutPage extends StatelessWidget {
final count = getIt<CountService>(); // 注入
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('About Page'),
),
body: Center(
child: StreamBuilder(
stream: count.n$,
builder: (context, snapshot) {
return Text(snapshot.data.toString());
}),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: count.add,
),
);
}
}
class CountService {
LoggerService loggerService = getIt<LoggerService>();
Stream<int> get n$ => _nSubject.stream;
Sink<int> get nSink => _nSubject.sink;
final _nSubject = BehaviorSubject<int>.seeded(0);
int _n = 0;
add() {
_n += 1;
if (_n % 3 == 0) {
loggerService.log(_n.toString());
}
nSink.add(_n);
}
dispose() {
_nSubject.close();
}
}
class LoggerService {
log(String info) {
print(info);
}
}
简单实现
class GetIt {
// service 储存器
final _factories = Map<Type, dynamic>();
// 确保不会被constructor
GetIt._();
static GetIt _instance;
static GetIt get instance {
_instance ??= GetIt._();
return _instance;
}
static GetIt get I => instance;
T get<T>() {
return _factories[T];
}
void registerSingleton<T>(T instance) {
_factories[T] = instance;
}
}
class ServiceA {
show() {
print('ServiceA');
}
}
class ServiceB {
show() {
print('ServiceB');
}
}
main(List<String> args) async {
GetIt getIt = GetIt.instance;
getIt.registerSingleton<ServiceA>(ServiceA());
getIt.registerSingleton<ServiceB>(ServiceB());
var serviceA = getIt.get<ServiceA>();
var serviceB = getIt.get<ServiceB>();
serviceA.show(); // ServiceA
serviceB.show(); // ServiceB
}