How to Create a TextField in Flutter
Text inputs are very important components of a mobile app. They allow users to enter text so that they can fill out a form or send a message. The TextField widget is used to create text inputs in Flutter.
In this Flutter tutorial, let’s go through how to create text input as well as how to retrieve the value from text input.
You have to use the stateful widget as TextField is a controlled widget. It’s better to use TextEditingController with TextField to retrieve the values entered in the inputs. Then you just need to pass the created controller to the TextInput widget.
TextField(
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
)
I have a TextField and a button in the following example. When the button is pressed the retrieved text from the input is shown as Snackbar. So, go through the code below for a better understanding of TextField in Flutter.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter TextInput Tutorial'),
),
body: const MyStatefulWidget());
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(children: <Widget>[
TextField(
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
),
ElevatedButton(
child: const Text('Retrieve Text'),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(_controller.text)));
},
),
]),
)));
}
}
Following is the output of the Flutter text input example.
I hope this Flutter tutorial on TextField will help you. Thank you for reading!
7 Comments