mirror of
https://github.com/flutter/samples.git
synced 2025-11-08 22:09:06 +00:00
## Pre-launch Checklist - [x] I read the [Flutter Style Guide] _recently_, and have followed its advice. - [x] I signed the [CLA]. - [x] I read the [Contributors Guide]. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-devrel channel on [Discord]. <!-- Links --> [Flutter Style Guide]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/wiki/Chat [Contributors Guide]: https://github.com/flutter/samples/blob/main/CONTRIBUTING.md Co-authored-by: Mark Thompson <2554588+MarkTechson@users.noreply.github.com> Co-authored-by: David Iglesias <ditman@gmail.com> Co-authored-by: Mark Thompson <2554588+MarkTechson@users.noreply.github.com> Co-authored-by: David Iglesias <ditman@gmail.com>
71 lines
1.8 KiB
Dart
71 lines
1.8 KiB
Dart
import 'package:flutter/material.dart';
|
|
|
|
class TextFieldDemo extends StatefulWidget {
|
|
const TextFieldDemo({super.key, required this.text});
|
|
final ValueNotifier<String> text;
|
|
|
|
@override
|
|
State<TextFieldDemo> createState() => _TextFieldDemoState();
|
|
}
|
|
|
|
class _TextFieldDemoState extends State<TextFieldDemo> {
|
|
late TextEditingController textController;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Initial value of the text box
|
|
textController = TextEditingController.fromValue(
|
|
TextEditingValue(
|
|
text: widget.text.value,
|
|
selection: TextSelection.collapsed(offset: widget.text.value.length)
|
|
)
|
|
);
|
|
// Report changes
|
|
textController.addListener(_onTextControllerChange);
|
|
// Listen to changes from the outside
|
|
widget.text.addListener(_onTextStateChanged);
|
|
}
|
|
|
|
void _onTextControllerChange() {
|
|
widget.text.value = textController.text;
|
|
}
|
|
|
|
void _onTextStateChanged() {
|
|
textController.value = TextEditingValue(
|
|
text: widget.text.value,
|
|
selection: TextSelection.collapsed(offset: widget.text.value.length),
|
|
);
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
super.dispose();
|
|
textController.dispose();
|
|
widget.text.removeListener(_onTextStateChanged);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
|
title: const Text('Text Field'),
|
|
),
|
|
body: Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(14.0),
|
|
child: TextField(
|
|
controller: textController,
|
|
maxLines: null,
|
|
decoration: const InputDecoration(
|
|
border: OutlineInputBorder(),
|
|
hintText: 'Type something!',
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|