Flutter – Passing Information to custom Button Widget

I’m trying to make a Custom Button Widget to reuse it in my code.

Within my page I’m calling the button like this:

import 'package:app/components/MyCustomButton.dart';
[...]
const MyCustomButton(
   title: 'Title of the button',
   type: 'primary'
),

the complete Source of MyCustomButton is below. The Issue I’m having is when displaying Text that was defined in the MyCustomButton.dart file the button works perfectly fine. Now I don’t want to display static text but instead text that I am passing from the screen file (e.g.: title variable)

When changing the static text

FROM                                     TO
-------------------------------------------------------------------------------
const Text(                         ->   const Text(
  'Login',                          ->     title,
  style: TextStyle(                 ->     style: TextStyle(
    color: Colors.white,            ->       color: Colors.white,
    fontSize: 20,                   ->       fontSize: 20,
    fontWeight: FontWeight.bold,    ->       fontWeight: FontWeight.bold,
  ),                                ->     ),
),                                  ->   ),

from ‘Login’ to title (which I want to pass) the ide throws "Not a constant expression" at me, even if I’m changing it to const title. I’m thankful for any explaination on what I’m missing here and what I’m doing wrong.

Thanks a lot!

import 'package:flutter/material.dart';

class MyCustomButton extends StatelessWidget{

  final String title; 
  final String type; 

  const MyCustomButton({
    super.key,
    required this.title,
    required this.type,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(35, 15, 35, 15),
      margin: const EdgeInsets.symmetric(horizontal: 20),
      decoration: const BoxDecoration(
        color: Color.fromRGBO(112, 143, 164, 1),
        borderRadius: BorderRadius.all(Radius.circular(4)),
      ),
      child: const Text(
        'Login',
        style: TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
    
  }
}

>Solution :

have you tried removing const from "const Text"?

child: Text(
        title,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),

Leave a Reply