Flutter - 基于reflectable反射以及调用

Flutter默认不允许反射。可以利用基于reflectable反射以及调用。

  1. 引入类库
1
2
dependencies:
reflectable: ^3.0.10
  1. 反射帮助类
1
2
3
4
5
6
7
8
9
import 'package:reflectable/reflectable.dart';
class Reflector extends Reflectable {
const Reflector()
: super(
invokingCapability,
declarationsCapability,
typeRelationsCapability,
libraryCapability); // Request the capability to invoke methods.
}
  1. 反射注解类
1
2
3
4
5
6
7
8
9
10
11
12
13
import 'package:odindio/reflector.dart';
import 'package:reflectable/mirrors.dart';
const odinReflectable = Reflector();
class OdinReflect {
static T reflectInstanceFromMap<T>(Map<String, dynamic> map,
{methodName = "fromJson"}) {
//反射T类型
ClassMirror classMirror = odinReflectable.reflectType(T) as ClassMirror;
// 调用工厂构造函数
var instance = classMirror.newInstance(methodName, [map]) as T;
return instance;
}
}
  1. model类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import 'package:json_annotation/json_annotation.dart';
import 'package:odindio/odin_reflect.dart';
part 'post_model.g.dart';
//反射注解
@odinReflectable
@JsonSerializable()
class PostModel {
final int? code;
final String? message;
final List<Data>? data;

PostModel({
this.code,
this.message,
this.data,
});

factory PostModel.fromJson(Map<String, dynamic> json) =>
_$PostModelFromJson(json);

@override
Map<String, dynamic> toJson() => _$PostModelToJson(this);

@override
fromJson(Map<String, dynamic> json) {
// TODO: implement fromJson
throw UnimplementedError();
}
}

@JsonSerializable()
class Data {
final int? id;
final String? stuName;
final int? age;

Data({
this.id,
this.stuName,
this.age,
});

factory Data.fromJson(Map<String, dynamic> json) =>
_$DataFromJson(json);

Map<String, dynamic> toJson() => _$DataToJson(this);
}
  1. 具体使用:
1
2
3
4
import 'odindio_test.reflectable.dart';
void main(){
initializeReflectable();
}
1
2
3
4
T dioResultToModel<T>(dynamic data){
var value = OdinReflect.reflectInstanceFromMap<T>(data);
return value;
}
终端执行 生成反射辅助类
1
flutter pub run build_runner clean && flutter pub run build_runner build --delete-conflicting-outputs