text
stringlengths
1
372
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
widget build(BuildContext context) {
const appTitle = 'form styling demo';
return MaterialApp(
title: appTitle,
home: scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatelessWidget {
const MyCustomForm({super.key});
@override
widget build(BuildContext context) {
return column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <widget>[
const padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'enter a search term',
),
),
),
padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'enter your username',
),
),
),
],
);
}
}
<code_end>
for more information on input validation, see the
building a form with validation recipe.
<topic_end>
<topic_start>
retrieve the value of a text field
in this recipe,
learn how to retrieve the text a user has entered into a text field
using the following steps:
<topic_end>
<topic_start>
1. create a TextEditingController
to retrieve the text a user has entered into a text field,
create a TextEditingController
and supply it to a TextField or TextFormField.
important: call dispose of the TextEditingController when
you’ve finished using it. this ensures that you discard any resources
used by the object.
<code_start>
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds the data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
// create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
widget build(BuildContext context) {
// fill this out in the next step.
}
}
<code_end>
<topic_end>
<topic_start>
2. supply the TextEditingController to a TextField
now that you have a TextEditingController, wire it up
to a text field using the controller property:
<code_start>
return TextField(