Flutter 中 FractionallySizedBox

143 阅读1分钟

FractionallySizedBox 是 Flutter 中的一个布局小部件,用于根据父部件的大小来调整其子部件的大小。它允许你指定子部件在父部件中所占的百分比大小,从而创建灵活的布局。

FractionallySizedBox 的主要参数包括:

  • widthFactor:子部件宽度相对于父部件宽度的比例(范围为 0.0 到 1.0)。
  • heightFactor:子部件高度相对于父部件高度的比例(范围为 0.0 到 1.0)。
  • alignment:子部件在父部件中的对齐方式,默认为居中对齐。

下面是一个简单的示例代码,演示如何使用 FractionallySizedBox

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FractionallySizedBox Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 200,
                height: 200,
                color: Colors.blue,
                child: FractionallySizedBox(
                  widthFactor: 0.5,
                  heightFactor: 0.5,
                  alignment: Alignment.center,
                  child: Container(
                    color: Colors.red,
                    child: Center(
                      child: Text(
                        'FractionallySizedBox',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个固定大小为 200x200 的蓝色容器,并在其中包含了一个 FractionallySizedBoxFractionallySizedBox 的子部件是一个红色的容器,它的宽度和高度都相对于父容器的一半,即它的 widthFactorheightFactor 都被设置为 0.5。这使得红色容器会在蓝色容器内居中显示,并且宽度和高度都是父容器宽度和高度的一半。

FractionallySizedBox 可以帮助你根据父部件的大小动态调整子部件的大小,从而创建更加灵活和响应式的布局。