创建网格列表
在某些情况下,您可能希望将项目显示为网格,而不是顺序排列的普通列表。为此,请使用GridView
widget。
开始使用网格的最简单方法是使用GridView.count()
构造函数,因为它允许您指定所需的行数或列数。
为了可视化GridView
的工作原理,生成一个包含100个widget的列表,这些widget显示它们在列表中的索引。
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,
),
);
}),
),
),
);
}
}