Flutter-Expanded布局组件

2022-05-25  本文已影响0人  阿博聊编程
配图来自网络,如侵必删

ExpandedFlutter当中使用非常高的组件之一,可以动态调整child组件的尺寸,以及动态填充剩余空间,常见的开发中和Row或者Column组件组合起来使用。

源码

  const Expanded({
    Key? key,
    int flex = 1,
    required Widget child,
  }) : super(key: key, flex: flex, fit: FlexFit.tight, child: child);

属性说明

这里针对源码做出相应的属性说明,熟悉控件的属性方便大家的使用:

属性名称 属性说明
child 子组件
flex 弹性系数,默认是1

示例代码

Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 100,
            height: 100,
            color: Colors.redAccent,
          ),
          Container(
            width: 100,
            height: 100,
            color: Colors.blueAccent,
          ),
          Expanded(
            child: Container(
              width: 100,
              height: 100,
              color: Colors.yellowAccent,
            ),
          )
        ],
      ),

效果如下:


image.png

完整的示例代码

以下的代码,可以直接复制到编译器去运行,方便小伙伴查看运行结果或者直接使用:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Expanded Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 100,
            height: 100,
            color: Colors.redAccent,
          ),
          Container(
            width: 100,
            height: 100,
            color: Colors.blueAccent,
          ),
          Expanded(
            child: Container(
              width: 100,
              height: 100,
              color: Colors.yellowAccent,
            ),
          )
        ],
      ),
    );
  }
}

上一篇下一篇

猜你喜欢

热点阅读