当前位置: 首页 > news >正文

flutter开发实战-jsontodart及 生成Dart Model类

flutter开发实战-jsontodart及 生成Dart Model类。
在开发中,经常遇到请求的数据Json需要转换成model类。这里记录一下Jsontodart生成Dart Model类的方案。

一、JSON生成Dart Model类

在开发中经常用到将json转成map或者list。通过json.decode() 可以方便 JSON 字符串转为 List/Map

{"name": "Bruce","age": 20
}

转换成Map

Map<String, dynamic> user = json.decode(json);

在自定义类中经常将请求封装,最后将请求转换成Map通过Dio请求服务器。

class UserInfoReq {int? id;int? timestamp;UserInfoReq({this.id, this.timestamp});UserInfoReq.fromJson(Map<String, dynamic> json) {id = json['id'];timestamp = json['timestamp'];}Map<String, dynamic> toJson() {final Map<String, dynamic> data = new Map<String, dynamic>();data['id'] = this.id;data['timestamp'] = this.timestamp;return data;}
}

使用json_annotation、json_serializable、build_runner插件生产Json对应的Dart model

一、引入插件json_annotation、json_serializable、build_runner

在pubspec.yaml引入相应的插件json_annotation、json_serializable、build_runner

dependencies:flutter:sdk: flutterflutter_localizations:sdk: flutter# The following adds the Cupertino Icons font to your application.# Use with the CupertinoIcons class for iOS style icons.cupertino_icons: ^1.0.2# JSON注解json_annotation: ^4.8.0dev_dependencies:flutter_test:sdk: flutter# JSON转modeljson_serializable: ^6.6.1build_runner: ^2.3.3

二、将Json转成Dart

在开发中经常用到Jsontodart,这里使用的是一下两个
https://javiercbk.github.io/json_to_dart/
https://caijinglong.github.io/json2dart/index_ch.html

将一下Json转成对应的类

{
"name":"Bruce",
"age":20
}

对应的dart类

import 'package:json_annotation/json_annotation.dart'; part 'user_info_dto.g.dart';()class UserInfoDto extends Object {(name: 'name')String name;(name: 'age')int age;UserInfoDto(this.name,this.age,);factory UserInfoDto.fromJson(Map<String, dynamic> srcJson) => _$UserInfoDtoFromJson(srcJson);Map<String, dynamic> toJson() => _$UserInfoDtoToJson(this);}

由于这里用到了json_annotation,需要使用命令生成’user_info_dto.g.dart’文件

通过在项目根目录下运行:

flutter packages pub run build_runner build

这触发了一次性构建,可以在需要时为我们的 Model 生成 json 序列化代码,它通过我们的源文件,找出需要生成 Model 类的源文件(包含@JsonSerializable 标注的)来生成对应的 .g.dart 文件。

在这里插入图片描述

三、小结

flutter开发实战-jsontodart及 生成Dart Model类。使用json_annotation、json_serializable、build_runner插件生产Json对应的Dart model。

学习记录,每天不停进步。

http://www.lryc.cn/news/103593.html

相关文章:

  • C++复刻:[流光按钮]+[悬浮波纹按钮]
  • CompletableFuture 详解
  • el-table数据处理
  • IPv4网络用户访问IPv6网络服务器
  • 程序员是怎么记住代码的?
  • 华为云NFS使用API删除大文件目录
  • 国家金融监督管理总局明确将数据安全管理纳入操作风险管理范畴
  • .asScala爆红
  • SOLIDWORKS Utilities应用
  • 发现的宝藏开源软件
  • 【八】mybatis 日志模块设计
  • Python-如何使用正则表达式
  • 分解质因子,将一个不小于2的整数分解质因数,例如,输入90,则输出:90=2*3*3*5
  • C语言,vs各种报错分析(不断更新)
  • AR开发平台 | 探索AR技术在建筑设计中的创新应用与挑战
  • 小白到运维工程师自学之路 第六十集 (docker的概述与安装)
  • SpringBoot 集成 Elasticsearch
  • 【ES】使用日志记录
  • svn还原本地代码
  • zore-shot,迁移学习和多模态学习
  • 【Golang 接口自动化07】struct转map的三种方式
  • 华为数通HCIA-网络模型
  • 端口的解说
  • “深入了解Spring Boot: 快速构建微服务应用的利器“
  • 华为OD机试 Java 实现【批量处理任务】【2023 B卷 200分】,二分查找
  • C# 2的幂
  • linux vi指令大全
  • jdk8使用okhttp发送http2请求
  • virbr是什么设备
  • MyBatis缓存-提高检索效率的利器--二级缓存