在 Flutter 1.12.1 版本ancestorInheritedElementForWidgetOfExactType被弃用之后。我们getElementForInheritedWidgetOfExactType现在应该使用。如何编辑它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; //deprecated
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;
}
Run Code Online (Sandbox Code Playgroud)
我_typeOf现在摆脱变量了吗?这种变化有什么好处?
使用context.getElementForInheritedWidgetOfExactType<_BlocProviderInherited<T>>().widget它应该可以工作。
就好处而言,文档基本上是一样的,尽管有人可以纠正我,但我没有看到任何区别。您应该能够摆脱_typeOf变量。
| 归档时间: |
|
| 查看次数: |
3953 次 |
| 最近记录: |