Flutter 案例学习Flutter中文社区Flutter圈子

Flutter 案例学习之:GridView

2018-09-11  本文已影响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

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,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读