美文网首页
Flutter基础控件之GridView

Flutter基础控件之GridView

作者: 青年别来无恙 | 来源:发表于2020-02-02 22:50 被阅读0次

    简单介绍

    GridView是一个网格布局的Widget。

    用法

    1、GridView.count
    class GridViewCountDemo extends StatelessWidget {
      List<Widget> _gridItems(int length) {
        return List.generate(length, (int index) {
          return Container(
            alignment: Alignment(0.0, 0.0),
            color: Colors.grey,
            child: Text(
              'Item $index',
              style: TextStyle(
                color: Colors.red,
                fontSize: 20.0,
              ),
            ),
          );
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return GridView.count(
          crossAxisCount: 2, /
          crossAxisSpacing: 10.0,
          mainAxisSpacing: 10.0,
          children: _gridItems(100),
        );
      }
    }
    
    2、GridView.extent
    class GridViewExtentDemo extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        List<Widget> _gridItems(int length) {
          return List.generate(length, (int index) {
            return Container(
              color: Colors.green,
              alignment: Alignment(0.0, 0.0),
              child: Text(
                'item $index',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
            );
          });
        }
    
        return GridView.extent(
          maxCrossAxisExtent: 200.0, // 相当于网格宽度
          crossAxisSpacing: 10.0,
          mainAxisSpacing: 10.0,
          children: _gridItems(50),
        );
      }
    }
    
    3、GridView.builder

    网格数量可以自由配置

    class GridViewBuildDemo extends StatelessWidget {
      Widget _gridItem(BuildContext context, int index) {
        return Container(
          child: Image.network(
            posts[index].imageUrl,
            fit: BoxFit.cover,
          ),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return GridView.builder(
            padding: EdgeInsets.all(20.0),
            itemCount: posts.length,
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    //          crossAxisCount: 3,
              maxCrossAxisExtent: 200,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
            ),
            itemBuilder: _gridItem);
      }
    }
    

    效果图

    GridView

    相关文章

      网友评论

          本文标题:Flutter基础控件之GridView

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