To get input feedback from user we will use TextField widget in flutter. TextField widget is same as TextInput. We have seen TextField on almost every mobile and web application.
Flutter TextField Retrieve Entered Value
1. Defining a TextEditingController. It is used to hold entered value of TextField.
final textInputName = TextEditingController();
2. Define a Empty string. We will use this string to show entered text in Text widget.
String output = '';
3. Defining a function, In this function we will store textInputName entered value into string.
getInput() {
setState(() {
output = textInputName.text;
});
}
4. Creating 1 Text, 1 TextField and 1 Button widget. First text display the entered text.
Column(children: <Widget> [
Text("Typed Text is = $output", style: const TextStyle(fontSize: 24)),
Container(
margin: const EdgeInsets.all(22),
child: TextField(
controller: textInputName,
autocorrect: true,
decoration: const InputDecoration(hintText: 'Type Here...'),
)),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
),
onPressed: getInput,
child: const Text('Retrieve TextField Value'),
),
])
Source code for main.dart file:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: App())));
}
}
class App extends StatefulWidget {
const App({super.key});
@override
AppState createState() => AppState();
}
class AppState extends State < App > {
final textInputName = TextEditingController();
String output = '';
getInput() {
setState(() {
output = textInputName.text;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(children: < Widget < [
Text("Typed Text is = $output", style: const TextStyle(fontSize: 24)),
Container(
margin: const EdgeInsets.all(22),
child: TextField(
controller: textInputName,
autocorrect: true,
decoration: const InputDecoration(hintText: 'Type Here...'),
)),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
),
onPressed: getInput,
child: const Text('Retrieve TextField Value'),
),
]))));
}
}
Screenshots:
Comments
Post a Comment