flutter bloc基于InheritedWidget应用
2020-10-16 本文已影响0人
翟小乙
BLoC:
BLoC表示为业务逻辑组件 (Business Logic Component),而原理就是对StreamController的封装和延申出PublishSubject(普通广播的streamcontroll,可监听多次(默认异步)),BehaviorSubject(缓存最新一次事件的广播流控制器),ReplaySubject(缓存多个数据的广播流控制器,可以设定上限),做一个笔记,方便日后查看!
我们举一个例子说一下用法:
context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;在flutter新版上方法已经过期。
过期方法:
static T of<T extends BlocBase>(BuildContext context){
final type = _typeOf<_BlocProviderInherited<T>>();
_BlocProviderInherited<T> provider =
context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;
return provider?.bloc;
}
新方法:
static T of<T extends BlocBase>(BuildContext context){
// final type = _typeOf<_BlocProviderInherited<T>>();
_BlocProviderInherited<T> provider =
context.getElementForInheritedWidgetOfExactType<_BlocProviderInherited<T>>()?.widget;
return provider?.bloc;
}
构造BlocProvider
import 'package:flutter/material.dart';
Type _typeOf<T>() => T;
abstract class BlocBase {
void dispose();
}
class BlocProvider<T extends BlocBase> extends StatefulWidget {
BlocProvider({
Key key,
@required this.child,
@required this.bloc,
}): super(key: key);
final Widget child;
final T bloc;
@override
_BlocProviderState<T> createState() => _BlocProviderState<T>();
static T of<T extends BlocBase>(BuildContext context){
final type = _typeOf<_BlocProviderInherited<T>>();
_BlocProviderInherited<T> provider =
context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;
return provider?.bloc;
}
}
class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>>{
@override
void dispose(){
widget.bloc?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context){
return new _BlocProviderInherited<T>(
bloc: widget.bloc,
child: widget.child,
);
}
}
class _BlocProviderInherited<T> extends InheritedWidget {
_BlocProviderInherited({
Key key,
@required Widget child,
@required this.bloc,
}) : super(key: key, child: child);
final T bloc;
@override
bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
}
BlocProvider和之前一样正常使用:
T t = BlocProvider.of<T>(context);
LoginBloc loginBloc = BlocProvider.of<LoginBloc>(context);