-
-
Notifications
You must be signed in to change notification settings - Fork 542
/
dynamic_fields.dart
123 lines (116 loc) · 3.51 KB
/
dynamic_fields.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
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
class DynamicFields extends StatefulWidget {
const DynamicFields({Key? key}) : super(key: key);
@override
State<DynamicFields> createState() => _DynamicFieldsState();
}
class _DynamicFieldsState extends State<DynamicFields> {
final _formKey = GlobalKey<FormBuilderState>();
final List<Widget> fields = [];
String savedValue = '';
@override
void initState() {
savedValue = _formKey.currentState?.value.toString() ?? '';
super.initState();
}
@override
Widget build(BuildContext context) {
return FormBuilder(
key: _formKey,
// IMPORTANT to remove all references from dynamic field when delete
clearValueOnUnregister: true,
child: Column(
children: <Widget>[
const SizedBox(height: 20),
FormBuilderTextField(
name: 'name',
validator: FormBuilderValidators.required(),
decoration: const InputDecoration(
label: Text('Started field'),
),
),
...fields,
const SizedBox(height: 10),
Row(
children: <Widget>[
Expanded(
child: MaterialButton(
color: Theme.of(context).colorScheme.secondary,
child: const Text(
"Submit",
style: TextStyle(color: Colors.white),
),
onPressed: () {
_formKey.currentState!.saveAndValidate();
setState(() {
savedValue =
_formKey.currentState?.value.toString() ?? '';
});
},
),
),
const SizedBox(width: 20),
Expanded(
child: MaterialButton(
color: Theme.of(context).colorScheme.secondary,
child: const Text(
"Add field",
style: TextStyle(color: Colors.white),
),
onPressed: () {
setState(() {
fields.add(NewTextField(
name: 'name_${fields.length}',
onDelete: () {
setState(() {
fields.removeAt(fields.length - 1);
});
},
));
});
},
),
),
],
),
const Divider(height: 40),
Text('Saved value: $savedValue'),
],
),
);
}
}
class NewTextField extends StatelessWidget {
const NewTextField({
super.key,
required this.name,
this.onDelete,
});
final String name;
final VoidCallback? onDelete;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Expanded(
child: FormBuilderTextField(
name: name,
validator: FormBuilderValidators.minLength(4),
decoration: const InputDecoration(
label: Text('New field'),
),
),
),
IconButton(
icon: const Icon(Icons.delete_forever),
onPressed: onDelete,
),
],
),
);
}
}