创建网格列表
在某些情况下,你可能希望以网格形式显示你的项目,而不是一个接一个的普通项目列表。对于此任务,请使用 GridView
小部件。
开始使用网格最简单的方法是使用 GridView.count()
构造函数,因为它允许你指定所需的行数或列数。
为了可视化 GridView
的工作方式,生成一个包含 100 个小部件的列表,这些小部件显示它们在列表中的索引。
dart
GridView.count(
// Create a grid with 2 columns.
// If you change the scrollDirection to horizontal,
// this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the list.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: TextTheme.of(context).headlineSmall,
),
);
}),
),
互动示例
#import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Grid List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(title: const Text(title)),
body: GridView.count(
// Create a grid with 2 columns.
// If you change the scrollDirection to horizontal,
// this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the list.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: TextTheme.of(context).headlineSmall,
),
);
}),
),
),
);
}
}