Flutter Widget 之InheritedWidget

344 阅读1分钟

将数据从一个widget传递到另一个widget 可能会变得很混乱

class One extends StatelessWidget {
    One(this.colors);
    final List<Color> colors;
    Widget build (BuildContext context) => Two(colors);
}

class Two extends StatelessWidget {
    Two(this.colors);
    final List<Color> colors;
    Widget build(BuildContext context) => Three(colors);
}

InheritedWidget允许任何子级widget访问该数据,从而避免了传递数据的麻烦,需要时就可以查找它

首先,创建您自己的扩展InheritedWidget的类,以在应用程序中传递数据

直接向您的类别添加要存储的数据的字段,然后过会儿再查找。

然后,您将添加两个方法of方法是一种可从子级widget更轻松地访问InheritedWidget数据地惯例

class ColorInfo extends InheritedWidget {
    final List<Color> colors;
    ColorInfo({this.colors, Widget child}) : super(child: child);

    static ColorInfo of(BuildContext context) =>
        context.inheritFromWidgetOfExactType(ColorInfo) as ColorInfo;
}
...
ColorInfo(child: One())

// Some other widget in app

Widget build(BuildContext context) {
    var colors = ColorsInfo.of(context).colors;
    // Do something with colors
}

第二种方法是updateShouldNotify

class ColorInfo extends InheritedWidget {
    ColorInfo({this.colors, Widget myChild})
        :super(child: myChild);
    final List<Color> colors;
    bool updateShouldNotify(
        ColorInfo oldWidget) =>
            oldWIdget.colors != color;
    static ColorInfo of(BuildCOntext context) =>
        context.inheritedFromWidgetOfExactTyoe(
        ColorInfo) as Storage;
}

这告诉Flutter当数据更改时是否应该重绘依赖于数据地widget

使用oldwidget参数,您可以将InheritedWidget中地先前数据与新数据进行比较

bool updateShouldNotify(
    ColorInfo oldWidget) => oldWidget.colors != colors;

如果您需要修改在widget树较下方地数据,则可以将InheritedWidget与valueNotifier或changeNotifier之类的东西组合在一起,但这可能会变得复杂

因此,对于这些情况请考虑使用provider

例如提供程序或范围模型来节省一些样板

如果想了解有关InheritedWidget的内容,或者关于Flutter的其他功能,请访问flutter.dev

原文翻译自视频:视频地址