Flutter 案例学习之:GridView

GitHub:https://github.com/happy-python/flutter_demos/tree/master/gridview_demo

在 ListView 中,如果将屏幕的方向变成横屏,效果将如下图所示:

                                                      ListView 横屏

如果采用 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,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

 

posted @ 2018-12-17 11:16  星辰之力  阅读(693)  评论(0编辑  收藏  举报