GitHub:https://github.com/happy-python/flutter_demos/tree/master/gridview_demo
在 ListView 中,如果将屏幕的方向变成横屏,效果将如下图所示:
如果采用 GridView 布局,效果将如下图所示:
GridView 横屏
项目整体结果图:
lib/pages/homepage.dart
判断设备的方向
Widget _getHomePageBody(BuildContext context) {
// 纵向
if (MediaQuery.of(context).orientation == Orientation.portrait) {
return MyListView(_allCities);
} else {
return MyGridView(_allCities);
}
}
lib/widget/mygridview.dart
- 最常用的网格布局 GridView.count
- 使用
InkWell
包装Card
,利用onTap
处理点击事件
import 'package:flutter/material.dart';
import 'package:gridview_demo/model/city.dart';
import 'package:gridview_demo/utils.dart';
class MyGridView extends StatelessWidget {
final List<City> allCities;
MyGridView(this.allCities);
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 3,
padding: EdgeInsets.all(10.0),
children: allCities.map((City city) {
return _getGridViewItemUI(context, city);
}).toList(),
);
}
Widget _getGridViewItemUI(BuildContext context, City city) {
return InkWell(
onTap: () {
showSnackBar(context, city);
},
child: Card(
elevation: 4.0,
child: Column(
children: <Widget>[
Image.asset(
city.image,
fit: BoxFit.cover,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
city.name,
style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold),
),
Text(
city.country,
style: TextStyle(
fontSize: 13.0,
),
),
Text(
"Population: ${city.population}",
style: TextStyle(
fontSize: 11.0,
),
),
],
),
],
),
),
);
}
}
网友评论