【Flutter】【GridView】 GridView 滚动列表

widget名字:GridView

之前学习的listview 等都是一行一个widget 的,但是如果你需要给你治一行有N个widget 的情况呢?


功能:

功能:

  1. 滚动列表,大部分同listview

使用实例和代码:

import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
// import 'dart:js';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class Car {
  const Car({
    required this.name,
    required this.imageUrl,
  });

  final String name;
  final String imageUrl;
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;
  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //模型数组,图片的地址
  final List<Car> datas = [
    const Car(
      name: '保时捷918 Spyder',
      imageUrl:
          'https://upload-images.jianshu.io/upload_images/2990730-7d8be6ebc4c7c95b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
    ),
    const Car(
      name: '兰博基尼Aventador',
      imageUrl:
          'https://img0.baidu.com/it/u=248838925,2520884714&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281',
    ),
    const Car(
      name: '法拉利Enzo',
      imageUrl:
          'https://img0.baidu.com/it/u=2100209512,2318272656&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
    ),
    const Car(
      name: 'Zenvo ST1',
      imageUrl:
          'https://img0.baidu.com/it/u=2100209512,2318272656&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
    ),
    const Car(
      name: '迈凯伦F1',
      imageUrl:
          'https://img1.baidu.com/it/u=1986361094,4267690672&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281',
    ),
    const Car(
      name: '萨林S7',
      imageUrl:
          'https://img1.baidu.com/it/u=4009522506,1625354802&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313',
    ),
    const Car(
      name: '科尼赛克CCR',
      imageUrl:
          'https://img1.baidu.com/it/u=4274211425,2430518865&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
    ),
    const Car(
      name: '布加迪Chiron',
      imageUrl:
          'https://img0.baidu.com/it/u=1477511855,2249772407&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=888',
    ),
    const Car(
      name: '轩尼诗Venom GT',
      imageUrl:
          'https://img2.baidu.com/it/u=2860007480,1034201436&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
    ),
    const Car(
      name: '西贝尔Tuatara',
      imageUrl:
          'https://img0.baidu.com/it/u=426493897,1352349043&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
    )
  ];
  late final ScrollController _scrollController;
  
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = ScrollController()
      ..addListener(() {
        //监听滚动的距离
        print(_scrollController.offset);
      });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text(widget.title),
      // ),
      body:



          //   children: List.generate(
          //       datas.length,
          //       (index) =>
          // Container(
          //             key: ValueKey(index),
          //             decoration: const BoxDecoration(
          //                 color: Colors.transparent,
          //                 borderRadius: BorderRadius.all(Radius.circular(10))),
          //             child: Card(
          //               clipBehavior: Clip.antiAlias, //抗锯齿
          //               // shape: RoundedRectangleBorder(
          //               //     borderRadius: BorderRadius.circular(15)),//圆角,下面是图片无法实现圆角功能
          //               elevation: 10,

          //               child: Image.network(
          //                 datas[index].imageUrl,
          //                 loadingBuilder: (context, child, loadingProgress) {
          //                   if (loadingProgress == null) {
          //                     return child;
          //                   }
          //                   return const CupertinoActivityIndicator();
          //                 },
          //                 fit: BoxFit.cover,
          //               ),
          //             ),
          //           )),
          // )
          GridView.builder(
              controller: _scrollController, //添加监听,同list view
              itemCount: datas.length, //指定数据量
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3, //交叉轴的widget 数量是
                  mainAxisSpacing: 10, //主轴间距
                  crossAxisSpacing: 10 //交叉轴的间距
                  ),
              itemBuilder: (context, int index) {
                return Container(
                    decoration: const BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Card(
                      clipBehavior: Clip.antiAlias, //抗锯齿
                      // shape: RoundedRectangleBorder(
                      //     borderRadius: BorderRadius.circular(15)),//圆角,下面是图片无法实现圆角功能
                      elevation: 10,

                      child: Image.network(
                        datas[index].imageUrl,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) {
                            return child;
                          }
                          return const CupertinoActivityIndicator();
                        },
                        fit: BoxFit.cover,
                      ),
                    ));
              }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _scrollController.animateTo(0,
              duration: Duration(seconds: 1), curve: Curves.easeInOut);
        },
        child: const Icon(Icons.arrow_circle_up),
      ),
    );
  }
}

    //下面的这种方式,比较适合数量widget 不多的情况如果比较多的话,还是需要告知下widget 的总量,flutter 才能更好的性能来处理

  GridView(
   //gridDelegate参数控制子控件的排列
   //SliverGridDelegateWithFixedCrossAxisCount: 交叉轴固定数量的情况
     //SliverGridDelegateWithMaxCrossAxisExtent:交叉轴 方向尽量的大,可以设置主轴和交叉轴的数量
    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
       crossAxisCount: 3, //交叉轴的widget 数量是
    mainAxisSpacing: 10, //主轴间距
     crossAxisSpacing: 10 //交叉轴的间距
  ),

截图:

运行结果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值