今天要介紹flutter cookbook裡的list技巧,list相關的技巧也非常容易被使用到
有時候可能會想用grid layout的方式顯示list,在flutter裡如果想用grid layout顯示widget的話,使用GridView widget非常方便,使用grid最簡單的方法是使用GridView.count()
構造函數,因為它可以讓你指定所需的row數或column數
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: Theme.of(context).textTheme.headline5,
),
);
}),
),
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: Theme.of(context).textTheme.headline5,
),
);
}),
),
),
);
}
}
參考資料:
https://docs.flutter.dev/cookbook/lists/grid-lists