深圳外贸网站,做任务免费领取东西的网站,网页布局图片,网站设计计划书flutter开发实战-jsontodart及 生成Dart Model类。 在开发中#xff0c;经常遇到请求的数据Json需要转换成model类。这里记录一下Jsontodart生成Dart Model类的方案。
一、JSON生成Dart Model类
在开发中经常用到将json转成map或者list。通过json.decode() 可以方便 JSON 字…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
MapString, dynamic user json.decode(json);在自定义类中经常将请求封装最后将请求转换成Map通过Dio请求服务器。
class UserInfoReq {int? id;int? timestamp;UserInfoReq({this.id, this.timestamp});UserInfoReq.fromJson(MapString, dynamic json) {id json[id];timestamp json[timestamp];}MapString, dynamic toJson() {final MapString, dynamic data new MapString, 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;JsonSerializable()class UserInfoDto extends Object {JsonKey(name: name)String name;JsonKey(name: age)int age;UserInfoDto(this.name,this.age,);factory UserInfoDto.fromJson(MapString, dynamic srcJson) _$UserInfoDtoFromJson(srcJson);MapString, 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。
学习记录每天不停进步。