Flutter 案例学习之:GridView

作者: 与蟒唯舞 | 来源:发表于2018-09-11 17:24 被阅读7次

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

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

    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,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }
    }
    

    相关文章

      网友评论

        本文标题:Flutter 案例学习之:GridView

        本文链接:https://www.haomeiwen.com/subject/vgoxgftx.html