-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathajv_example.dart
180 lines (160 loc) · 5.79 KB
/
ajv_example.dart
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_js/flutter_js.dart';
import 'ajv_result_screen.dart';
import 'form.dart';
class AjvExample extends StatefulWidget {
final JavascriptRuntime jsRuntime;
const AjvExample(this.jsRuntime, {Key? key}) : super(key: key);
@override
_AjvExampleState createState() => _AjvExampleState();
}
class _AjvExampleState extends State<AjvExample> {
String _jsResult = '';
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
final GlobalKey<FormState> _formKey = GlobalKey();
final GlobalKey<FormWidgetState> _formWidgetKey = GlobalKey();
Future<dynamic>? _loadingFuture;
@override
void initState() {
super.initState();
_loadingFuture = initJsEngine();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initJsEngine() async {
// loads ajv only once into the jsRuntime
var ajvIsLoaded = widget.jsRuntime
.evaluate("""var ajvIsLoaded = (typeof ajv == 'undefined') ?
"0" : "1"; ajvIsLoaded;
""").stringResult;
if (kDebugMode) {
print("AJV is Loaded $ajvIsLoaded");
}
if (ajvIsLoaded == "0") {
try {
String ajvJS = await rootBundle.loadString("assets/js/ajv.js");
widget.jsRuntime.evaluate("""var window = global = globalThis;""");
widget.jsRuntime.evaluate(ajvJS + "");
widget.jsRuntime.evaluate("""
var ajv = new global.Ajv({ allErrors: true, coerceTypes: true });
ajv.addSchema(
{
required: ["name", "age","id", "email", "student", "worker"],
"properties": {
"id": {
"minimum": 0,
"type": "number"
},
"name": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"minimum": 0,
"type": "number"
},
"student": {
"type": "boolean"
},
"worker": {
"type": "boolean"
}
}
}, "obj1");
""");
} on PlatformException catch (e) {
if (kDebugMode) {
print('Failed to init js engine: ${e.details}');
}
}
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
}
_validateFunctionFor() {
return (String field, String valor, Map<String, String> data) {
var formData = {};
formData.addAll(data);
formData.removeWhere((key, value) => value.toString().trim().isEmpty);
if (valor.isNotEmpty) {
formData[field] = valor;
}
final expression = """ajv.validate(
"obj1",
${json.encode(formData)}
);
JSON.stringify(ajv.errors);
""";
JsEvalResult jsResult = widget.jsRuntime.evaluate(expression);
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_jsResult = jsResult.stringResult;
});
});
final valueResult = json.decode(jsResult.stringResult);
final List<ValidationResult> result = ValidationResult.listFromJson(
valueResult is int ? [] : valueResult ?? []);
final errorsForField = result
.where((element) =>
element.message!.contains(field) ||
element.params['missingProperty'] == field ||
element.dataPath == ".$field")
.toList();
return errorsForField;
};
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Ajv Example'),
),
body: FutureBuilder(
future: _loadingFuture,
builder: (_, snapshot) =>
snapshot.connectionState == ConnectionState.waiting
? const Center(child: Text('Aguarde...'))
: SingleChildScrollView(
child: Column(
children: <Widget>[
FormWidget(
operation: FormWidgetOperation.New,
formWidgetKey: _formWidgetKey,
formKey: _formKey,
validateFunction: _validateFunctionFor(),
fields: const [
'id',
'name',
'email',
'age',
"student",
"worker"
]),
],
),
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.info_outline),
onPressed: () async {
Navigator.of(_scaffoldKey.currentContext!).push(
MaterialPageRoute(
builder: (context) => AjvResultScreen(
"{\"errors\": ${_jsResult == "" ? null : _jsResult}}",
notRoot: false,
),
),
);
},
),
);
}
}