Flutter Stuff

How to set Icon on TextField Widget in Flutter App

How to set Icon on TextField Widget in Flutter App

Introduction

In Flutter, the TextField widget is a fundamental component used for user input. It provides a variety of features such as text editing, validation, and decoration. One common requirement in many applications is to display an icon inside the TextField widget. In this article, we will explore how to set an icon on the TextField widget in a Flutter app.

Adding Icon to TextField

To add an icon to the TextField widget, you can use the `prefixIcon` or `suffixIcon` properties. The `prefixIcon` is displayed at the beginning of the TextField, while the `suffixIcon` is displayed at the end.

Code Example

Here’s an example of how to use the `prefixIcon` and `suffixIcon` properties:

“`dart

import ‘package:flutter/material.dart’;

class MyWidget extends StatefulWidget {

@override

MyWidgetState createState() => MyWidgetState();

}

class _MyWidgetState extends State {

@override

Widget build(BuildContext context) {

return Scaffold(

body: Center(

child: TextField(

decoration: InputDecoration(

prefixIcon: Icon(Icons.search),

suffixIcon: Icon(Icons.clear),

border: OutlineInputBorder(),

),

),

),

);

}

}

“`

Customizing Icon Appearance

You can customize the appearance of the icon by using the `iconSize` and `iconColor` properties.

“`dart

prefixIcon: Icon(

Icons.search,

size: 24,

color: Colors.blue,

)

“`

Handling Icon Click

To handle the click event of the icon, you can wrap the `Icon` widget with a `GestureDetector` or `InkWell` widget.

“`dart

prefixIcon: InkWell(

child: Icon(Icons.search),

onTap: () {

// Handle icon click

},

)

“`

Conclusion

In this article, we have learned how to set an icon on the TextField widget in a Flutter app. By using the `prefixIcon` and `suffixIcon` properties, you can easily add icons to the TextField widget and customize their appearance. We have also seen how to handle the click event of the icon.

FAQ

1. How do I add an icon to the TextField widget in Flutter?

You can add an icon to the TextField widget using the `prefixIcon` or `suffixIcon` properties.

2. Can I customize the size and color of the icon?

Yes, you can customize the size and color of the icon using the `iconSize` and `iconColor` properties.

3. How do I handle the click event of the icon?

You can handle the click event of the icon by wrapping the `Icon` widget with a `GestureDetector` or `InkWell` widget.

4. Can I use a custom icon?

Yes, you can use a custom icon by providing a custom `Widget` to the `prefixIcon` or `suffixIcon` properties.

5. Is it possible to add multiple icons to the TextField widget?

No, you can only add one prefix icon and one suffix icon to the TextField widget.

Leave a Comment

Scroll to Top