Code前端首页关于Code前端联系我们

使用 Flutter GridView 组件创建

terry 2年前 (2023-09-23) 阅读数 65 #移动小程序

GridView 组件的多行列表。可滚动的二维空间数组。

使用无限加载下拉列表时,首先要用到的就是ListView组件。但如果要在一行中显示 2 列或更多列的下拉列表,则 GridView 组件更方便。如下图

Flutter GridView组件使用,打造多行列表

向服务器请求数据后,服务器往往会返回一个json字符串。如果我们想要更灵活的使用数据,就需要将json字符串转换为对象。由于flutter只向Map提供json。手写反序列化在大型项目中不稳定,可能会导致解析失败。最好使用 json_serializable 进行自动反序列化。

首先在文件中的dependency中添加json_annotation,在dev_dependency中添加json_serializable

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  json_annotation: ^2.0.0
  cached_network_image: ^0.5.1
  transparent_image: ^0.1.0
  dio: ^1.0.9
  video_player: ^0.7.2
  flutter_spinkit: ^2.1.0

dev_dependencies:
  build_runner: ^1.0.0
  json_serializable: ^2.0.0
  flutter_test:
    sdk: flutter

使用json_serializable方法创建模型类

创建模型

import 'package:json_annotation/';
part '';

@JsonSerializable()
class PicModel {
  PicModel(this.createdAt,this.publishedAt,this.type,this.url);

  String createdAt;
  String publishedAt;
  String type;
  String url;

  factory PicModel.fromJson(Map<String,dynamic> json) => _$PicModelFromJson(json);
}

这个文件不存在,现在没有代码。必须打开Container来为我们生成序列化模板。通过在项目根目录中运行 flutter packages pub run build_runner build,我们可以根据需要为模型生成 json 序列化代码。这会导致一次性构建,它会遍历我们的源文件,选择适当的文件并生成必要的序列化代码。

然后创建一个文件并创建一个基本结构。引入相关库

import 'package:flutter/';
import 'dart:io';
import 'dart:convert';
import 'package:flutter_yuan/models/';
import 'package:cached_network_image/';

class FindPage extends StatefulWidget{
  FindPage({Key key}):super(key:key);
  @override
  createState() => new _FindPageState();
}

class _FindPageState extends State<FindPage> {
  List<PicModel> picList = new List();
  int page = 1;
  @override
  void initState() {
    ();
    _getPicList();
  }
  @override
  Widget build(BuildContext context) {
    returnnew Scaffold(
      
    );
  }
}

我们需要通过_getPicList异步获取数据:

_getPicList() async{
    String url = '$page';
    var httpClient = new HttpClient();
    try {
      var req = await httpClient.getUrl((url));
      var res = await req.close();
      // print(res);if(res.statusCode == HttpStatus.OK) {
        var jsonString = await res.transform().join();//将结果转换成字符串拼接// print(jsonString);
        Map data = jsonDecode(jsonString);//格式化成Map对象        print(data);
        List pics = data['data'];
        List<PicModel> items = new List();
        for (var value in pics) {
          (new PicModel.fromJson(value));
        };
        setState(() {         this.picList.addAll(items);          
          this.page ++;
        });
      }
    } catch (e) {
      
    }
  }

然后创建一个Widget:

Widget build(BuildContext context) {
    returnnew Scaffold(
      appBar: new AppBar(
        title: new Text('美图'),
        centerTitle: true,
      ),
      body: new (
        padding: const EdgeInsets.all(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisSpacing: ,
          crossAxisSpacing: ,
        ),
        itemCount: picList.length,
        itemBuilder: (BuildContext context, int index) {
          if(index == picList.length - 1 ){
            _getPicList();
          }
          return buildItem(picList[index]);
        },
      ),
    );
  }

使用组件创建列表,通过gridDelegate属性添加列表样式。 crossAxisCount 属性可以设置每行的列数以创建瀑布布局。

buidItem 方法样式图像布局。

buildItem(item) {
    returnnew GestureDetector(
      onTap: () {
        (
          context, 
          new MaterialPageRoute(
            builder: (context) => 
            new Scaffold(
              appBar: new AppBar(
                title: new Text('图片详情'),
              ),
              body: new Center(
                child: new Container(
                  width: 300.0,
                  child: new CachedNetworkImage(
                    imageUrl: item.url,
                    fit: BoxFit.fitWidth,
                  ),
                )
              ),
            )
          )
        );
      },
      child: new CachedNetworkImage(
        errorWidget: new Icon(),
        imageUrl: item.url,
        fadeInDuration: new Duration(seconds: 3),
        fadeOutDuration: new Duration(seconds: 1),
      ),
    );
  }

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门