LayoutBuilder 是 Flutter 中的一个构建组件,用于根据父容器的约束对其子组件进行布局。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'LayoutBuilder Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('LayoutBuilder Example'),
        ),
        body: Center(
          child: Container(
            color: Colors.blue,
            child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                // 计算子组件的宽度和高度
                double width = constraints.maxWidth / 2;
                double height = constraints.maxHeight / 2;

                return Container(
                  width: width,
                  height: height,
                  color: Colors.red,
                  child: Center(
                    child: Text('Sub Widget'),
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

我们使用 LayoutBuilder 组件来根据父容器的约束动态计算子组件的大小。我们将子组件的宽度和高度都设置为父容器宽度的一半,这样子组件会占据父容器的一四分之一的空间,并且背景色为红色。

posted on 2023-12-19 14:26  鲤斌  阅读(345)  评论(0编辑  收藏  举报