GridView

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,    //一行显示4个
          childAspectRatio: 16 / 9  //方块比例
        ),
       itemBuilder: (_, index)=>Container(
         color: Colors.primaries[index%Colors.primaries.length],
       )),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

截屏2021-11-02 下午10.34.16

​ 使用SliverGridDelegateWithFixedCrossAxisCount时,屏幕一行显示的数量已经确定,但是当手机横过来时,就会出现不那么协调的情况,产生了格子的拉伸,而且没有起到显示更多内容的效果:

截屏2021-11-02 下午10.36.27

此时我们可以使用SliverGridDelegateWithMaxCrossAxisExtent:

gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
  maxCrossAxisExtent: 100,    //一个方块最多显示100像素
  childAspectRatio: 16 / 9,  //方块比例
  mainAxisSpacing: 4.0,     //主轴间距
  crossAxisSpacing: 2.0     //副轴间距
)

//这里也可以写成GridView.extent,直接指定maxCrossAxisExtent属性,可惜的是这样就不支持动态懒加载(builder)了

截屏2021-11-02 下午10.45.10