Flutter-獲取Widget尺寸的方式

想要獲取widget的尺寸,必須要等widget的layout結(jié)束之后才能取到,目前有三種方式

  • 通過BuildContext獲取
  • 通過GlobalKey獲取
  • 通過SizeChangedLayoutNotifier獲取

通過BuildContext獲取

widget的尺寸存在于context?.findRenderObject()?.paintBounds?.size中,過早獲取可能為空,需要延時(shí)獲取.在flutter1.7之前duration=Duration()就能獲取到,但是1.7之后必須要設(shè)置一百毫秒以上才行.

class FindSizeWidget extends StatefulWidget {
  @override
  _FindSizeWidgetState createState() => _FindSizeWidgetState();
}

class _FindSizeWidgetState extends State<FindSizeWidget> {

  @override
  Widget build(BuildContext context) {
    /// 延時(shí)一下,需要等state layout結(jié)束之后才能獲取size
    Future.delayed(Duration(milliseconds: 100), () {
      _printSize();
    });
    return _buildContentWidget();
  }
  Widget _buildContentWidget(){
    return Container(
      color: Colors.red,
      child: Text(
        '''
        1 ...            1    
        2 ...            2    
        3 ...            3    
        4 ...            4    
        ''',
        style: TextStyle(fontSize: 30),
        maxLines: null,
        softWrap: true,
      ),
    );
  }
  _printSize(){
    if (!mounted) return;
    var size = context?.findRenderObject()?.paintBounds?.size;
    print(size.toString());
  }
}

打印結(jié)果:
flutter: Size(277.0, 180.0)

通過GlobalKey獲取

FindSizeWidget增加構(gòu)造方法,通過外部傳入GlobalKey,方便以后尋找到FindSizeWidget.context對象.

class FindSizeWidget extends StatefulWidget {
  const FindSizeWidget({Key key}) : super(key:key);
}

注意一個(gè)GlobalKey只能對應(yīng)一個(gè)widget對象,當(dāng)心復(fù)用問題.

增加一個(gè)獲取尺寸的按鈕.點(diǎn)擊之后獲取尺寸.

  class _MyApp extends State<MyApp> {
  GlobalKey _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        FlatButton(
            onPressed: () {
              var size = _globalKey.currentContext
                  ?.findRenderObject()
                  ?.paintBounds
                  ?.size;
              print(size.toString());
            },
            child: Text("獲取尺寸")),
        FindSizeWidget(
          key: _globalKey,
        )
      ],
    );
  }
}

打印結(jié)果:
flutter: Size(277.0, 180.0)

通過SizeChangedLayoutNotifier獲取

使用SizeChangedLayoutNotifier方式,Widget會在layout結(jié)束之后會發(fā)出一個(gè)LayoutChangedNotification通知,我們只需要接收這個(gè)通知,即可獲取尺寸信息,但是SizeChangedLayoutNotifierRenderObject_RenderSizeChangedWithCallback類,它在第一次布局完成之后并不會發(fā)出通知,所以我們要自定義SizeChangedLayoutNotifier_RenderSizeChangedWithCallback兩個(gè)類.
_RenderSizeChangedWithCallback源碼部分:

@override
  void performLayout() {
    super.performLayout();
    // Don't send the initial notification, or this will be SizeObserver all
    // over again!
    if (_oldSize != null && size != _oldSize)
      onLayoutChangedCallback();
    _oldSize = size;
  }

修改_RenderSizeChangedWithCallback,只需要去掉_oldSize != null的判斷即可.

@override
  void performLayout() {
    super.performLayout();
    // Don't send the initial notification, or this will be SizeObserver all
    // over again!
    if (size != _oldSize)
      onLayoutChangedCallback();
    _oldSize = size;
  }

再修改_FindSizeWidgetStatebuild方法:

  @override
  Widget build(BuildContext context) {
    return NotificationListener<LayoutChangedNotification>(
      onNotification: (notification) {
        /// 收到布局結(jié)束通知,打印尺寸
        _printSize();
        /// flutter1.7之后需要返回值,之前是不需要的.
        return null;
      },
      child: CustomSizeChangedLayoutNotifier(
        child: _buildContentWidget(),
      ),
    );
  }

打印結(jié)果:
flutter: Size(277.0, 180.0)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容