In many application we have seen that after submitting the form all the TextField present on screen empty itself. This can be easily achievable in flutter with TextEditingController().clear method. This method will clear the associated TextField when invokes.
Flutter Clear TextField Entered Text on Button Click
1. Defining TextEditingController() for control TextField text.
final nameController = TextEditingController();
2. Creating a function clearTextField() and call Clear method.
clearTextField() {
nameController.clear();
}
3. Defining TextField and Button.
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget> [
Container(
// width: 260,
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: nameController,
decoration:
const InputDecoration(hintText: 'Type Name Here...'),
)),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
),
onPressed: clearTextField,
child: const Text('Clear TextField'),
),
],
),
Screenshots:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: App())));
}
}
class App extends StatefulWidget {
@override
AppState createState() => AppState();
}
class AppState extends State {
final nameController = TextEditingController();
clearTextField() {
nameController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
// width: 260,
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: nameController,
decoration:
const InputDecoration(hintText: 'Type Name Here...'),
)),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
),
onPressed: clearTextField,
child: const Text('Clear TextField'),
),
],
),
));
}
}
Comments
Post a Comment