Line data Source code
1 : library flutter_json_schema_form;
2 :
3 : import 'package:flutter/material.dart';
4 : import 'package:flutter_json_schema_form/controller/flutter_json_schema_form_controller.dart';
5 : import 'package:flutter_json_schema_form/flutter_json_schema_form.dart';
6 : import 'package:json_schema_document/json_schema_document.dart';
7 :
8 : /// A FormField generated from a JSON Schema property.
9 : class FlutterJsonSchemaFormField extends StatelessWidget {
10 2 : const FlutterJsonSchemaFormField.fromJsonSchema({
11 : Key? key,
12 : required this.jsonSchema,
13 : required this.path,
14 : required this.controller,
15 : this.editingControllerMapping,
16 2 : }) : super(key: key);
17 :
18 : final JsonSchema jsonSchema;
19 :
20 : final FlutterJsonSchemaFormController controller;
21 :
22 : final Map<String, dynamic>? editingControllerMapping;
23 :
24 : final List<String> path;
25 :
26 6 : String? get title => jsonSchema.title;
27 :
28 2 : @override
29 : Widget build(BuildContext context) {
30 4 : switch (jsonSchema.type) {
31 2 : case JsonSchemaType.string:
32 2 : return Padding(
33 : padding: const EdgeInsets.symmetric(vertical: 4),
34 2 : child: TextField(
35 2 : decoration: InputDecoration(
36 2 : labelText: title,
37 : ),
38 0 : onChanged: (value) {
39 0 : controller.updateValue(path, value);
40 : },
41 6 : controller: accessValue(path, editingControllerMapping),
42 : ),
43 : );
44 1 : case JsonSchemaType.number:
45 1 : return Padding(
46 : padding: const EdgeInsets.symmetric(vertical: 4),
47 1 : child: TextField(
48 1 : decoration: InputDecoration(
49 1 : labelText: title,
50 : ),
51 : keyboardType: TextInputType.number,
52 0 : onChanged: (value) {
53 0 : controller.updateValue(path, value);
54 : },
55 3 : controller: accessValue(path, editingControllerMapping),
56 : ),
57 : );
58 1 : case JsonSchemaType.object:
59 1 : return Column(
60 1 : children: [
61 : const SizedBox(height: 8),
62 1 : Padding(
63 : padding: const EdgeInsets.only(left: 32),
64 1 : child: FlutterJsonSchemaForm.fromJsonSchema(
65 1 : jsonSchema: jsonSchema,
66 : isInnerField: true,
67 1 : controller: controller,
68 1 : path: path,
69 : ),
70 : )
71 : ],
72 : );
73 : default:
74 1 : return Container();
75 : }
76 : }
77 : }
78 :
79 : /// this function nests into the map following the path,
80 : /// which is a list of each key to follow, finally, it returns the found value, or null if not found
81 2 : dynamic accessValue(List<String> path, dynamic map) {
82 2 : if (path.isEmpty) {
83 : return map;
84 : }
85 2 : final String key = path.first;
86 4 : if (map is Map && map.containsKey(key)) {
87 6 : return accessValue(path.sublist(1), map[key]);
88 : } else {
89 : return map;
90 : }
91 : }
|