首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

Flutter学习笔记八——GridView Widget

2024-12-19 来源:要发发知识网

认识GridView组件并简单使用

先看一个简单的例子,使用Text组件作为GrideView的item:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "GridView",
      home: Scaffold(
        appBar: AppBar(
          title: Text("GridView Widget"),
        ),
        body: GridView.count(
          crossAxisCount: 3,
          padding: EdgeInsets.all(10.0),
          crossAxisSpacing: 10.0,
          children: <Widget>[
            const Text("this is 1 item"),
            const Text("this is 2 item"),
            const Text("this is 3 item"),
            const Text("this is 4 item"),
            const Text("this is 5 item"),
          ],
        ),
      ),
    );
  }
}

效果如图:

GridView.jpg
使用GridView.count()方法创建GridView组件,
  • padding:表示内边距
  • crossAxisCount:表示每行显示的网格个数
  • crossAxisSpacing:表示每个网格之间的间距。

这样并不太直观,下面使用图片组件作为GrideView的item:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "GridView",
      home: Scaffold(
          appBar: AppBar(
            title: Text("GridView Widget"),
          ),
          body: GridView(
            padding: EdgeInsets.all(1.0),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                childAspectRatio: 0.75),
            children: <Widget>[
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover),
              
                  
                  fit: BoxFit.cover)
            ],
          )),
    );
  }
}

效果如图:


imgGrid.jpg
  • childAspectRatio: 表示宽高比,即宽是高的多少倍,0.75=3/4
  • mainAxisSpacing:可以理解为行间距
  • crossAxisSpacing:可以理解为列间距
显示全文