通过基础的 24 分栏,迅速简便地创建布局。
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: LayoutGrid(),
),
);
}
class LayoutGrid extends StatefulWidget {
const LayoutGrid({
super.key,
});
@override
State<LayoutGrid> createState() => _LayoutGridState();
}
class _LayoutGridState extends State<LayoutGrid> {
Color getRandomColor() {
return Colors.primaries[math.Random().nextInt(Colors.primaries.length)];
}
_buildSingleColor() {
return ColoredBox(
color: getRandomColor(),
);
}
@override
Widget build(BuildContext context) {
// return Align(
// child: SizedBox(
// height: 40,
// child: Flex(
// direction: Axis.horizontal,
// mainAxisSize: MainAxisSize.max,
// children: [
// ElCol(
// flex: 6,
// child: _buildSingleColor(),
// ),
// ElCol(
// flex: 6,
// child: _buildSingleColor(),
// ),
// ElCol(
// flex: 6,
// child: _buildSingleColor(),
// ),
// ElCol(
// flex: 6,
// child: _buildSingleColor(),
// ),
// ],
// ),
// ),
// );
// }
return ElRow(
constraints: BoxConstraints(
maxWidth: double.infinity, // 此处必须是一个确定的值,否则会出现意外的情况
maxHeight: 40,
),
children: [
ElCol(
flex: 6,
child: _buildSingleColor(),
),
ElCol(
flex: 12,
child: _buildSingleColor(),
),
ElCol(
flex: 3,
child: _buildSingleColor(),
),
ElCol(
flex: 3,
child: _buildSingleColor(),
),
],
);
}
}
class ElRow extends StatelessWidget {
const ElRow({super.key, required this.children, required this.constraints});
final BoxConstraints constraints;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return UnconstrainedBox(
child: ConstrainedBox(
constraints: constraints.tighten(
width:
math.min(MediaQuery.of(context).size.width, constraints.maxWidth),
height: constraints.maxHeight,
),
child: Flex(
direction: Axis.horizontal,
mainAxisSize: MainAxisSize.max,
children: children,
),
),
);
}
}
class ElCol extends StatelessWidget {
const ElCol({super.key, this.child, required this.flex});
final int flex;
final Widget? child;
@override
Widget build(BuildContext context) {
return Flexible(
fit: FlexFit.tight,
flex: flex,
child: SizedBox.expand(
child: child,
),
);
}
}