在Flutter
开发当中,我们可能需要实现以下需求:
组件实现各种定位
这篇博客主要分享容器组件的Align
的使用,希望对看文章的小伙伴有所帮助。
简单的示例代码
Align(
alignment: Alignment.center,
child: Container(
color: Colors.red,
width: 80,
height: 80,
),
),
效果图如下所示:
源码
const Align({
Key? key,
this.alignment = Alignment.center,
this.widthFactor,
this.heightFactor,
Widget? child,
}) : assert(alignment != null),
assert(widthFactor == null || widthFactor >= 0.0),
assert(heightFactor == null || heightFactor >= 0.0),
super(key: key, child: child)
属性说明
这里针对源码做出相应的属性说明,熟悉控件的属性方便大家的使用。
1.设置子控件:
child: Container(
color: Colors.red,
width: 80,
height: 80,
),
2.设置对齐方式,默认是居中对齐的:
alignment: Alignment.center,
3.设置Align
组件的宽高:
widthFactor: 2,
heightFactor: 2,
完整的代码
以下的代码,可以直接复制到编译器去运行,方便小伙伴查看运行结果或者直接使用:
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: 'Flutter Demo Home Page'),
);
}
}
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("Align组件的使用"),
),
body: Align(
alignment: Alignment.center,
child: Container(
color: Colors.red,
width: 80,
height: 80,
),
),
);
}
}