当前位置:   article > 正文

Flutter LayoutBuilder组件

flutter layoutbuilder

LayoutBuilder

通过 LayoutBuilder,我们可以在布局过程中拿到父组件传递的约束信息,然后我们可以根据约束信息动态的构建不同的布局。

比如我们实现一个响应式的 Column 组件 ResponsiveColumn,它的功能是当当前可用的宽度小于 200 时,将子组件显示为一列,否则显示为两列。简单来实现一下:

  1. class ResponsiveColumn extends StatelessWidget {
  2. const ResponsiveColumn({Key? key, required this.children}) : super(key: key);
  3. final List<Widget> children;
  4. @override
  5. Widget build(BuildContext context) {
  6. // 通过 LayoutBuilder 拿到父组件传递的约束,然后判断 maxWidth 是否小于200
  7. return LayoutBuilder(
  8. builder: (BuildContext context, BoxConstraints constraints) {
  9. if (constraints.maxWidth < 200) {
  10. // 最大宽度小于200,显示单列
  11. return Column(children: children, mainAxisSize: MainAxisSize.min);
  12. } else {
  13. // 大于200,显示双列
  14. var _children = <Widget>[];
  15. for (var i = 0; i < children.length; i += 2) {
  16. if (i + 1 < children.length) {
  17. _children.add(Row(
  18. children: [children[i], children[i + 1]],
  19. mainAxisSize: MainAxisSize.min,
  20. ));
  21. } else {
  22. _children.add(children[i]);
  23. }
  24. }
  25. return Column(children: _children, mainAxisSize: MainAxisSize.min);
  26. }
  27. },
  28. );
  29. }
  30. }
  31. class LayoutBuilderRoute extends StatelessWidget {
  32. const LayoutBuilderRoute({Key? key}) : super(key: key);
  33. @override
  34. Widget build(BuildContext context) {
  35. var _children = List.filled(6, Text("A"));
  36. // Column在本示例中在水平方向的最大宽度为屏幕的宽度
  37. return Column(
  38. children: [
  39. // 限制宽度为190,小于 200
  40. SizedBox(width: 190, child: ResponsiveColumn(children: _children)),
  41. ResponsiveColumn(children: _children),
  42. LayoutLogPrint(child:Text("xx")) // 下面介绍
  43. ],
  44. );
  45. }
  46. }

可以发现 LayoutBuilder 的使用很简单,但是不要小看它,因为它非常实用且重要,它主要有两个使用场景:

  1. 可以使用 LayoutBuilder 来根据设备的尺寸来实现响应式布局。
  2. LayoutBuilder 可以帮我们高效排查问题。比如我们在遇到布局问题或者想调试组件树中某一个节点布局的约束时 LayoutBuilder 就很有用。

打印布局时的约束信息

为了便于排错,我们封装一个能打印父组件传递给子组件约束的组件:

  1. class LayoutLogPrint <T>extends StatelessWidget {
  2.   final Widget child;
  3.   final T? tag;
  4.   const LayoutLogPrint({Key? key, required this.child, this.tag}) : super(key: key);
  5.  
  6.   @override
  7.   Widget build(BuildContext context) {
  8.     return LayoutBuilder(builder: (_,constraints){
  9.       // assert在编译release版本时会被去除
  10.       assert(() {
  11.         print('${tag ?? key ?? child}: $constraints');
  12.         return true;
  13.       }());
  14.       return child;
  15.     });
  16.   }
  17. }

这样,我们就可以使用 LayoutLogPrint 组件树中任意位置的约束信息,比如:

LayoutLogPrint(child:Text("xx"))
 控制台输出:

flutter: Text("xx"): BoxConstraints(0.0<=w<=428.0, 0.0<=h<=823.0)

可以看到 Text("xx") 的显示空间最大宽度为 428,最大高度为 823 。
 


获取父组件大小并布局容器LayoutBuilder

  1. LayoutBuilder(
  2. builder: (context,constraints){
  3. context为父级上下文
  4. constraints.biggest.height; 获取组件在父组件所能设置的最大高度
  5. contraints.maxWidth; 获取父组件宽度,高度同理
  6. return 组件
  7. }
  8. )

代码示例:

  1. LayoutBuilder(
  2. builder: (context,constraints){
  3. final endHeight=constraints.biggest.height;
  4. return GestureDetector(
  5. onVerticalDragDown: (text){ //当点击时会获取点击坐标
  6. print(endHeight);
  7. print(constraints.maxHeight);
  8. print(constraints.maxWidth);
  9. },
  10. onVerticalDragEnd: (text){
  11. print(text);
  12. },
  13. onVerticalDragCancel: (){
  14. print("取消");
  15. },
  16. child: Column(
  17. crossAxisAlignment: CrossAxisAlignment.center,
  18. mainAxisAlignment: MainAxisAlignment.center,
  19. children: <Widget>[
  20. Icon(Icons.search,size: 15,),
  21. GestureDetector(
  22. child:Text('A') ,
  23. onTap: (){
  24. scroll.animateTo(312, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
  25. },
  26. ),
  27. GestureDetector(
  28. child:Text('B') ,
  29. onTap: (){
  30. scroll.animateTo(478, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
  31. },
  32. ),
  33. GestureDetector(
  34. child:Text('C') ,
  35. onTap: (){
  36. scroll.animateTo(575, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
  37. },
  38. ),
  39. GestureDetector(
  40. child:Text('D') ,
  41. onTap: (){
  42. scroll.animateTo(741, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
  43. },
  44. ),
  45. Text('E'),
  46. Text('F'),
  47. Text('G'),
  48. Text('H'),
  49. Text('I'),
  50. Text('J'),
  51. Text('K'),
  52. Text('L'),
  53. Text('M'),
  54. Text('N'),
  55. Text('O'),
  56. Text('P'),
  57. Text('Q'),
  58. Text('R'),
  59. Text('S'),
  60. Text('T'),
  61. Text('U'),
  62. Text('V'),
  63. Text('W'),
  64. Text('X'),
  65. Text("Y"),
  66. Text("#")
  67. ],
  68. ),
  69. );
  70. },
  71. )

使用LayoutBuilder 用来获取父布局的尺寸大小

本文章的效果如下:

在这里插入图片描述

 1 核心代码是通过 LayoutBuilder来获取父窗口尺寸

  1. LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
  2.   double maxWidth = constraints.maxWidth;
  3.   double minWidth = constraints.minWidth;
  4.   double maxHeight = constraints.maxHeight;
  5.   double minHeight = constraints.minHeight;
  6.   if(maxWidth>400) {
  7.     return buildRow();
  8.   }
  9.   return buildColumn();
  10.   
  11. },)

2 全部代码实现

  1. class LayoutBuilderPage extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return Scaffold(
  5. body: Center(
  6. child: LayoutBuilder(
  7. builder: (BuildContext context, BoxConstraints constraints) {
  8. double maxWidth = constraints.maxWidth;
  9. double minWidth = constraints.minWidth;
  10. double maxHeight = constraints.maxHeight;
  11. double minHeight = constraints.minHeight;
  12. if (maxWidth > 400) {
  13. return buildRow();
  14. }
  15. return buildColumn();
  16. },
  17. ),
  18. ),
  19. );
  20. }
  21. Widget buildRow() {
  22. return Row(
  23. mainAxisAlignment: MainAxisAlignment.center,
  24. children: [
  25. ElevatedButton(onPressed: () {}, child: Text("右侧按钮")),
  26. SizedBox(
  27. width: 60,
  28. ),
  29. ElevatedButton(onPressed: () {}, child: Text("左侧按钮")),
  30. ],
  31. );
  32. }
  33. Widget buildColumn() {
  34. return Column(
  35. mainAxisAlignment: MainAxisAlignment.center,
  36. children: [
  37. ElevatedButton(onPressed: () {}, child: Text("右侧按钮")),
  38. SizedBox(
  39. height: 60,
  40. ),
  41. ElevatedButton(onPressed: () {}, child: Text("左侧按钮")),
  42. ],
  43. );
  44. }
  45. }

使用 LayoutBuilder 频繁Build

  1. return LayoutBuilder(builder: (ctx, constraints) {
  2. /// 这里返回出去的Widget,如果超出显示大小,一旦刷新时,这里就会频繁build。
  3. /// 解决方案:
  4. /// 第一次Build的时候,把constraints,保存为成员变量。
  5. /// 第二次不再通过LayoutBuilder获取constraints。
  6. });

解决方案:

  1. return LayoutBuilder(builder: (ctx, constraints) {
  2. this.constraints = constraints;
  3. return Container(color:Colors.black);
  4. });

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/268765
推荐阅读
相关标签
  

闽ICP备14008679号