m * n 布局,可以扩展马赛克效果,字体排版
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: MNLayout(column: 3, row: 4),
),
);
}
class MNLayout extends StatefulWidget {
const MNLayout({
super.key,
required this.column,
required this.row,
});
final int column;
final int row;
@override
State<MNLayout> createState() => _MNLayoutState();
}
class _MNLayoutState extends State<MNLayout> {
Color getRandomColor() {
return Colors.primaries[Random().nextInt(Colors.primaries.length)]
.withOpacity(0.2);
}
_buildSingleColor(int x, int y) {
int index = x * widget.column + y; // 从左到右 , 从上到下
return ColoredBox(
color: getRandomColor(),
child: Center(child: Text(index.toString())),
);
}
Widget getTotal() {
List<Widget> rows = [];
for (int j = 0; j < widget.column; j++) {
List<Widget> columns = [];
for (int i = 0; i < widget.row; i++) {
// if (i * widget.column + j == 10) {
// print(' j - $j , i - $i');
// }
columns.add(
Expanded(
// child: _buildSingleColor(j * widget.row + i), // 从上到下,从左到右
child: _buildSingleColor(i, j),
),
);
}
rows.add(
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columns,
),
),
);
}
Widget curRow = Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: rows,
);
return curRow;
}
@override
Widget build(BuildContext context) {
return Scaffold(body: getTotal());
}
}
/// ===
/// ==== n * m 的代码 Row[Expanded(Column),Expanded(Column),Expanded(Column)]
/// ====
Color getRandomColor() {
return Colors.primaries[Random().nextInt(Colors.primaries.length)];
}
Widget build2(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
Expanded(
child: ColoredBox(
color: getRandomColor(),
),
),
],
),
),
],
);
}