可以将InheritedWidget用作混合吗?

时间:2019-01-20 22:34:17

标签: dart flutter

我正在尝试查看是否可以添加围绕应用程序传递的常规导航行为,并且我发现InheritedWidget是避免在小部件树周围传递特定回调的理想选择,但是我越来越多地注意到我只能使用特定类类型的InheritedWidget才能使InheritedWidget模式起作用,而且我想知道是否有一种方法可以使用InheritedWidget作为mixin,或者是否有更好的方法替代。

我的应用看起来像这样,它在树上传递了一个回调

enter image description here

我现在有3个导航器,我需要介绍相同的方法,但现在要对其执行操作,我需要创建3个InheritedWidget导航器,但是问题在于,树下的任何窗口小部件都必须这样做

NavigatorA.of(context).pushWidget()

但是我更喜欢它是否是通用的GenericNavigator.of(context).pushWidget(),这样我的叶子小部件甚至不需要知道导航器对象的正确值,我很害怕实现这一点。 d需要能够将InheritedWidget用作mixin

这是所需的流程,没有传递回调

enter image description here

这是正确的策略还是有更好的方法? 如何将InheritedWidget用作混合?

2 个答案:

答案 0 :(得分:2)

否,您不能将InheritedWidget用作混合。

但是,您可以创建通用的InheritedWidget

class Provider<T> extends InheritedWidget {
  Provider({Key key, this.value, Widget child}) : super(key: key, child: child);

  final T value;

  @override
  bool updateShouldNotify(Provider<T> oldWidget) {
    return value != oldWidget.value;
  }
}

静态of方法的实现似乎有些棘手。由于没有语法来获取Provider<int>

的类型

幸运的是,使用一些解决方法是可行的:

Type _typeOf<T>() => T;

允许按照以下方式实现of方法:

static T of<T>(BuildContext context) {
  final type = _typeOf<Provider<T>>();
  Provider<T> provider = context.inheritFromWidgetOfExactType(type);
  return provider?.value;
}

答案 1 :(得分:0)

添加到@RémiRousselet的答案

使用Flutter 1.19+(其中已弃用某些inheritedWidget API)的情况,of现在应如下所示:

    static T of<T>(BuildContext context) {
      return context.dependOnInheritedWidgetOfExactType<Provider<T>>().value;
    }

由于api基于泛型,因此您不再需要_typeof技巧。

相关问题