flutter 之AspectRatio 按比例显示,aspectRatio属性设置宽高之比。
但是在Expand中要被强制占用整个空间,可以在里面加下ALign类,并用align属性调整放置的位置。
/// Flutter code sample for AspectRatio
// This examples shows how AspectRatio sets width when its parent's width
// constraint is infinite. Since its parent's allowed height is a fixed value,
// the actual width is determined via the given AspectRatio.
//
// Since the height is fixed at 100.0 in this example and the aspect ratio is
// set to 16 / 9, the width should then be 100.0 / 9 * 16.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
alignment: Alignment.center,
width: double.infinity,
height: 100.0,
child: AspectRatio(
aspectRatio: 16 / 9,
child: Container(
color: Colors.green,
),
),
);
}
}
本文介绍了如何在Flutter中使用AspectRatio组件来按比例设置子元素的宽度,尤其在Expand容器内的布局调整。通过实例演示了如何结合Align和aspectRatio属性,实现精确的自适应布局。
1261

被折叠的 条评论
为什么被折叠?



