flutterdart

How can I pass String as an argument in Dart?


Issue arises at line Text(textToDisplay)

I get the error Arguments of a constant creation must be constant expressions.

class IconText extends StatelessWidget {
  const IconText({super.key, required this.icon, required this.textToDisplay});

  final IconData icon;
  final String textToDisplay;

  @override
  Widget build(BuildContext context) {
    return const Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          Icons.male,
          size: 80,
          color: Colors.grey,
        ),
        SizedBox(height: 15),
        Text(textToDisplay)
      ],
    );
  }
}

I consume this widget like so

const Expanded(
              child: Row(
            children: [
              NewWidget(
                color: widgetColor,
                cardChild: IconText(icon: Icons.male, textToDisplay: "Male"),
              ),
              NewWidget(
                color: widgetColor,
                cardChild: IconText(icon: Icons.male, textToDisplay: "Female"),
              )
            ],
          )),

How can I fix this error?


Solution

  • You have to remove the const of your column

    class IconText extends StatelessWidget {
      const IconText({super.key, required this.icon, required this.textToDisplay});
    
      final IconData icon;
      final String textToDisplay;
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.male,
              size: 80,
              color: Colors.grey,
            ),
            const SizedBox(height: 15),
            Text(textToDisplay)
          ],
        );
      }
    }