Search code examples
flutterdartflutter-getx

TextButton in different file not recognized as TextButton


I am using GetX in a Flutter project.

Using a function like Get.snackbar() will allow me to show a SnackBar, in which I want to inlcude a button using mainButton. This button has to be of type TextButton. Because I am using this type of SnackBar in a lot of parts of my project, I would like to have TextButton to be called from another file.

I create a file like:

import 'package:flutter/material.dart';

class SnackbarTextButton extends StatelessWidget {
  final String text;

  const SnackbarTextButton({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: ButtonStyle(
        overlayColor: MaterialStateColor.resolveWith((states) => Colors.transparent),
        splashFactory: NoSplash.splashFactory,
      ),
      onPressed: () {},
      child: Text(
        text,
        style: const TextStyle(
          fontSize: 12,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}

I include it where I use my SnackBar, but I get the error: The argument type 'SnackbarTextButton' can't be assigned to the parameter type 'TextButton?'.

How can I tell my file that I am actually returning a TextButton? How can I change the type of the widget that I am building on another file to match in this case TextButton?

Thanks in advance.


Solution

  • you can make a helper method instead of StatelessWidget, because if the required type is a TextButton? then using StatelessWidget, you should extend or implement the TextButton type:

    class SnackbarTextButton extends TextButton {// ...}
    

    But this will give you extra unnecessary work for your case because, you can simply make a helper method to return that TextButton widget you want:

    TextButton snackbarTextButton ({required this.text}) {
     return TextButton(
      style: ButtonStyle(
        overlayColor: MaterialStateColor.resolveWith((states) => Colors.transparent),
        splashFactory: NoSplash.splashFactory,
      ),
      onPressed: () {},
      child: Text(
        text,
        style: const TextStyle(
          fontSize: 12,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
     }
    

    then call it like this:

    snackbarTextButton(text: "exampleText"), // this will be valid for TextButton type