Home > Mobile >  How to correctly pass IconData as and argument to a custom widget
How to correctly pass IconData as and argument to a custom widget

Time:02-14

I have a custom wrapper around the TextFormField widget, I want to be able to pass in a material Icon as an argument to the constructor. However, when trying to pass the IconData into the Icon constructor I get an error: Arguments of constant creation must be constant expressions.

import 'package:flutter/material.dart';

class LoginFormField extends StatelessWidget {
   const LoginFormField({Key? key,
    required this.fillColor,
    required this.textColor,
    required this.borderColor,
    required this.onChanged,
    required this.validateField,
    required this.icon
  }) : super(key: key);

  final Color fillColor;
  final Color textColor;
  final Color borderColor;
  final Function(String) onChanged;
  final FormFieldValidator validateField;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        fillColor: fillColor,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(width: 16, color: borderColor)
        ),
        labelText: 'Enter your username',
        prefixIcon: const Padding(
          padding: EdgeInsets.only(top: 15), // add padding to adjust icon
          child: Icon(icon)
        ),
      ),
      validator: validateField,
      onChanged: onChanged,
    );
  }
}

Any help on how to correctly pass in an icon as an argument?

CodePudding user response:

You're passing icondata correctly. The error is telling you the that prefixicon can not be const.

prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),

Remove the const as icon is argument to your widget which is not const. Make it

prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),

CodePudding user response:

It is because you're setting the widget as const.

Remove const from the following code:

prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),

it becomes:

prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),
  • Related