Home > Net >  How can I make a Stateless TextInputWidget with a optional Icon as input argument?
How can I make a Stateless TextInputWidget with a optional Icon as input argument?

Time:11-20

I am trying to create a RoundedInputField as a StatelessWidget. I am still learning both Dart and Flutter but I am a bit stuck at the moment. So where it all started is that I want to optionally choose a prefixIcon from outside the class. I created a helper function buildInputDecorator in order to handle the creation of InputDecoration based on iconData is set or not. I have a couple of compilation errors that I am not sure how to tackle. I have added the errors as comments.

My code is:

import 'package:flutter/material.dart';

class RoundedInputField extends StatelessWidget {
  final IconData? iconData;
  const RoundedInputField({super.key, this.iconData});

  InputDecoration buildInputDecorator(String hint) {
    if (iconData != null) {
      return const InputDecoration(
        hintText: hint,             //Invalid constant value.dart(invalid_constant)
        prefixIcon: Icon(iconData), //Arguments of a constant creation must be constant expressions.
      );
    }

    return const InputDecoration(
      hintText: hint,              //Invalid constant value.dart(invalid_constant)
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        color: Color.fromRGBO(73, 152, 203, 1),
      ),
      padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 10.0),
      child: const TextField(
        decoration: buildInputDecorator("Email"), //Invalid constant value.dart(invalid_constant)
      ),
    );
  }
}

CodePudding user response:

I try your code, why not just like this instead of making a function :

import 'package:flutter/material.dart';

class RoundedInputField extends StatelessWidget {
  final IconData? iconData;
  final String? hint;
  const RoundedInputField({super.key, this.iconData, this.hint});


  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        color: Color.fromRGBO(73, 152, 203, 1),
      ),
      padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 10.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: hint,
          prefixIcon: iconData != null ? Icon(iconData) : null
        ), 
      ),
    );
  }
}
  • Related