本文最后更新于 49 天前,其中的信息可能已经有所发展或是发生改变。
网格GridView:
count方法:
GridView.count(
crossAxisCount: 2,//列数
children: const [
Icon(Icons.ac_unit),
Icon(Icons.airport_shuttle),
Icon(Icons.all_inclusive),
Icon(Icons.beach_access),
Icon(Icons.cake),
Icon(Icons.free_breakfast)
],
)
extend方法:
GridView.extent(
maxCrossAxisExtent: 500,//行最大长度
children: const [
Icon(Icons.ac_unit),
Icon(Icons.airport_shuttle),
Icon(Icons.all_inclusive),
Icon(Icons.beach_access),
Icon(Icons.cake),
Icon(Icons.free_breakfast),
Icon(Icons.ac_unit),
Icon(Icons.airport_shuttle),
Icon(Icons.all_inclusive),
Icon(Icons.beach_access),
Icon(Icons.cake),
Icon(Icons.free_breakfast),
],
)
静态网格效果:
动态网格:builder,用法与ListView.builder基本相同
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
),
itemCount: 20,
itemBuilder: (context, index) {
return Card(
child: Center(
child: Text('Grid Item $index'),
),
);
},
);
同时学了一下Expanded()的使用,用于包裹Column/Row等的内部组件,适当的给子组件按比例分割,避免空间冲突导致报错,例如将屏幕分半,上半部分显示一个列表,下半部分显示一个网格:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyScreen(),
);
}
}
class MyScreen extends StatelessWidget {
const MyScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Split Screen Example'),
),
body: const Column(
children: [
Expanded(
child: MyListView(),
),
Expanded(
child: MyGridView(),
),
],
),
);
}
}
class MyListView extends StatelessWidget {
const MyListView({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
);
}
}
class MyGridView extends StatelessWidget {
const MyGridView({super.key});
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
),
itemCount: 20,
itemBuilder: (context, index) {
return Card(
child: Center(
child: Text('Grid Item $index'),
),
);
},
);
}
}
效果: