free geoip
48

How to Clear Form Input Fields in Dart Easily

Clearing form inputs in Dart is essential for improving user experience in Flutter applications. When working with TextFormField, resetting input…

Clearing form inputs in Dart is essential for improving user experience in Flutter applications. When working with TextFormField, resetting input fields can be done using TextEditingController. This tutorial will guide you step-by-step on how to clear form fields manually and programmatically, using best practices in Flutter.

clear form input in Dart

Here’s a complete example demonstrating how to create a simple form and clear the input fields with a button press.

1. Main Dart File (main.dart)

import 'package:flutter/material.dart';
import 'form_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Clear Form Example',
      home: FormScreen(),
    );
  }
}

2. Form Screen (form_screen.dart)

import 'package:flutter/material.dart';

class FormScreen extends StatefulWidget {
  @override
  _FormScreenState createState() => _FormScreenState();
}

class _FormScreenState extends State<FormScreen> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();

  void _clearInputs() {
    _nameController.clear();
    _emailController.clear();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Clear Form Inputs')),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextFormField(
              controller: _nameController,
              decoration: InputDecoration(labelText: 'Name'),
            ),
            TextFormField(
              controller: _emailController,
              decoration: InputDecoration(labelText: 'Email'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _clearInputs,
              child: Text('Clear Form'),
            ),
          ],
        ),
      ),
    );
  }
}

By using TextEditingController.clear(), you can reset the fields anytime the user taps a button or after form submission.

You can also explore Flutter’s official documentation for further best practices related to form handling.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *