如何使用SizeChangedLayoutNotifier?

pro*_*bie 12 flutter flutter-layout

Wrap在我的SliverAppBar. 现在,当 Wrap 的大小发生变化(动态)时,我需要收到通知,这样我就可以相应地更改 SliverAppBar 中的 flexSpace 的高度。

我阅读了SizeChangedLayoutNotifier的文档,但我不太明白如何使用它。我Wrap小时候把我包裹在 a 中SizeChangedLayoutNotifier,但对我来说,非常不清楚如何用 捕获通知NotificationListener<SizeChangedLayoutNotification>。我找不到任何代码示例。

我非常感谢您的帮助:) 谢谢!

pro*_*bie 13

我终于弄清楚了,并将在这里为其他遇到同样问题的人发布解决方案。

我把我的Wrap内心是这样的:

new NotificationListener<SizeChangedLayoutNotification>(
   onNotification: gotNotification,
   child: SizeChangedLayoutNotifier(
       key: _filterBarChangeKey,
       child: Wrap( // my WRAP stuff)
   )
);
Run Code Online (Sandbox Code Playgroud)

我的回调如下:

bool gotNotification(SizeChangedLayoutNotification notification) {
    // change height here
    _filterBarChangeKey = GlobalKey();
}
Run Code Online (Sandbox Code Playgroud)

我还从这里找到了另一个解决方案,根本不使用 SizeChangedLayoutNotification 来解决我的问题。对我来说这更好。我只是将我的小部件包装在一个MeaserSize提供onSizeChanged回调的小部件中。

typedef void OnWidgetSizeChange(Size size);

class MeasureSize extends StatefulWidget {
  final Widget child;
  final OnWidgetSizeChange onChange;

  const MeasureSize({
    Key key,
    @required this.onChange,
    @required this.child,
  }) : super(key: key);

  @override
  _MeasureSizeState createState() => _MeasureSizeState();
}

class _MeasureSizeState extends State<MeasureSize> {
  var widgetKey = GlobalKey();

  @override
  Widget build(BuildContext context) {

    WidgetsBinding.instance
        .addPostFrameCallback((_) =>  widget.onChange(widgetKey.currentContext.size));

    return Container(
      key: widgetKey,
      child: widget.child,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您要使用“widget.onChange”(例如:setState)刷新相同的小部件,在构建时调用“widget.onChange”(无论您是否使用“WidgetsBinding.instnace.addPostFrameCallback”)可能会导致循环,所以我建议使用两者的组合:“initState”上的“addPostFramecallback”来获取初始高度,然后使用“NotificationListener”进行后续更改。 (2认同)