How To Add Clear Button To Text Field Input Using Flutter App

admin_img Posted By Bajarangi soft , Posted On 02-11-2020

Receiving and acting on user input is essential to the success of most apps these days. If the experience of typing words into a form field or search bar is frustrating, user’s may be discouraged from using your app. For instance, maybe the input field doesn’t auto-capitalize words even though it should. Or maybe deleting the current value in a form can only be done by hitting the backspace button seventeen times.

How To Add Clear Button To Text Field Input Using Flutter App

Clear Button To Text Field Input
Complete Code For  Clear Button To Text Field Input In Flutter
main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textFieldController = TextEditingController();

  _onClear() {
    setState(() {
      _textFieldController.text = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.pink,
        title: Text('Clear TextField'),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 25.0),
          child: TextField(
            controller: _textFieldController,
            decoration: InputDecoration(
              enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
              borderSide: BorderSide(color: Colors.black26),
              ),
              focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
              borderSide: BorderSide(color: Colors.grey),
              ),
              contentPadding: EdgeInsets.all(4),
              hintText: 'Enter name',
              hintStyle: TextStyle(color: Colors.black45,fontSize: 14),
              suffix: IconButton(
                icon: Icon(Icons.cancel),
                onPressed: _onClear,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Related Post