GitHub:https://github.com/happy-python/flutter_demos/tree/master/gridview_demo
在 ListView 中瓶蚂,如果將屏幕的方向變成橫屏弱贼,效果將如下圖所示:
如果采用 GridView 布局,效果將如下圖所示:
項目整體結(jié)果圖:
lib/pages/homepage.dart
判斷設(shè)備的方向
Widget _getHomePageBody(BuildContext context) {
// 縱向
if (MediaQuery.of(context).orientation == Orientation.portrait) {
return MyListView(_allCities);
} else {
return MyGridView(_allCities);
}
}
lib/widget/mygridview.dart
- 最常用的網(wǎng)格布局 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,
),
),
],
),
],
),
),
);
}
}