Skip to content

Commit 77db01e

Browse files
docs: add clear text field example to readme
1 parent e1b1d7f commit 77db01e

File tree

1 file changed

+38
-15
lines changed

1 file changed

+38
-15
lines changed

README.md

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -307,24 +307,47 @@ FormBuilderDropdown<String>(
307307
),
308308
```
309309

310-
Or if is allowed by the field, set a value like this:
310+
Or reset value like this:
311311

312312
```dart
313-
FormBuilderTextField(
314-
name: 'age',
315-
decoration: InputDecoration(
316-
labelText: 'Age',
317-
suffixIcon: IconButton(
318-
icon: const Icon(Icons.plus_one),
319-
onPressed: () {
320-
_formKey.currentState!.fields['age']
321-
?.didChange('14');
313+
class ClearFormBuilderTextField extends StatefulWidget {
314+
const ClearFormBuilderTextField({super.key});
315+
316+
@override
317+
State<ClearFormBuilderTextField> createState() =>
318+
_ClearFormBuilderTextFieldState();
319+
}
320+
321+
class _ClearFormBuilderTextFieldState
322+
extends State<ClearFormBuilderTextField> {
323+
final ValueNotifier<String?> text = ValueNotifier<String?>(null);
324+
final textFieldKey = GlobalKey<FormBuilderFieldState>();
325+
326+
@override
327+
Widget build(BuildContext context) {
328+
return FormBuilderTextField(
329+
autovalidateMode: AutovalidateMode.always,
330+
name: 'age',
331+
key: textFieldKey,
332+
onChanged: (value) {
333+
text.value = value;
322334
},
323-
),
324-
),
325-
initialValue: '13',
326-
keyboardType: TextInputType.number,
327-
),
335+
decoration: InputDecoration(
336+
labelText: 'Age',
337+
suffixIcon: ValueListenableBuilder<String?>(
338+
valueListenable: text,
339+
child: IconButton(
340+
onPressed: () => textFieldKey.currentState?.didChange(null),
341+
tooltip: 'Clear',
342+
icon: const Icon(Icons.clear),
343+
),
344+
builder: (context, value, child) =>
345+
(value?.isEmpty ?? true) ? const SizedBox() : child!,
346+
),
347+
),
348+
);
349+
}
350+
}
328351
```
329352

330353
## Support

0 commit comments

Comments
 (0)