Install

In pubspec.yaml add:

dependencies: ... Built_value: ^ 7.1.0 dev_dependencies:... Build_runner: ^ 1.10.0 built_value_generator: ^ 7.1.0# pub getCopy the code

Usage

Define serializable models:

import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'user_info.g.dart';
abstract class UserInfo implements Built<UserInfo,UserInfoBuilder>{  
    static Serializer<UserInfo> get serializer => _$userInfoSerializer;
    String get phone;
    String get userName;
    UserInfo._();  
    factory UserInfo([void Function(UserInfoBuilder) updates]) = _$UserInfo;
}
Copy the code

library serializers;
import 'package:built_value/serializer.dart';
import 'package:flutter_app/api/result.dart';
import 'package:flutter_app/models/user_info.dart';
part 'serializer.g.dart'; @SerializersFor(const [ UserInfo, ... ] ) final Serializers serializers = _$serializers;Copy the code

$ flutter packages pub run build_runner buildCopy the code

The UserInfoBuilder class and _$UserInfo are generated

The main function

  1. Immutable model.
  2. serialization
  3. Enumeration implementation

Parsing json:

String json = '{"phone": "123231313131","userName": "userName"}'; final standardSerializers = (serializers.toBuilder().. addPlugin(new StandardJsonPlugin())).build(); final value =standardSerializers.deserializeWith(UserInfo.serializer, jsonDecode(json));Copy the code

Serialization:

var userInfo = new UserInfo((b) => b .. userName ='kk'  
    ..phone = '123456');
print(jsonEncode(serializers.serialize(login)));Copy the code