Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom TextFormField Flutter suffix icon

I want to make TextFormField with optional suffixIcon (IconButton) how to do that?

import 'package:flutter/material.dart';

class CustomTextFormField extends StatelessWidget {
  final String text;
  final String hintText;
  final bool obsecureText;
  final IconButton iconButton;

  const CustomTextFormField({
    Key? key,
    required this.text,
    required this.hintText,
    this.obsecureText = false,
    this.iconButton = IconButton() //I dont know the logic
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(text),
        const SizedBox(height: 8.0),
        Form(
          child: TextFormField(
            obscureText: obsecureText,
            decoration: InputDecoration(
              suffixIcon: iconButton,
              hintText: hintText,
            ),
          ),
        ),
        const SizedBox(height: 24.0),
      ],
    );
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can create nullable IconButton and a callback method for default iconButton‘s onPressed,

final IconButton? iconButton;
final VoidCallback? callback;

const CustomTextFormField({
  this.iconButton,
  this.callback,
  ....
 }
suffixIcon: iconButton ??
    IconButton(
      onPressed: callback,
      icon: const Icon(Icons.ac_unit),
    ),

Or

final IconButton iconButton;
final VoidCallback? callback;

CustomTextFormField({
  this.callback,
  Key? key,
  required this.text,
  required this.hintText,
  this.obsecureText = false,
})  : iconButton = IconButton(
        onPressed: callback,
        icon: const Icon(Icons.ac_unit),
      ),
      super(key: key);

It is necessary to use callback for button, else you may go for state-management.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading