Home > Software design >  How to make SnackBar width flexible based on text in flutter?
How to make SnackBar width flexible based on text in flutter?

Time:06-12

Snackbar width can only be set with parameter width, otherwise it uses full screen width.

Is there a way I can make it flexible?

EDIT: Something like this below.

enter image description here

enter image description here

CodePudding user response:

The trick is here I am using transparent background. You can create a method passing context and size.

showMySnackBar({
  required BuildContext context,
  required double width,
  double? height,
}) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      padding: EdgeInsets.zero,
      content: Column(
        mainAxisSize: MainAxisSize.min, // needed for flexible height
        children: [
          Container(
            alignment: Alignment.center,
            width: width,
            height: height,
            color: Colors.green,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("MY snack"),
              ],
            ),
          ),
        ],
      ),
    ),
  );
}

And use

 showMySnackBar(context: context, width: 400);

CodePudding user response:

There's a very useful package that you can use- fluttertoast.

Simply write -

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
    );

You can add toastLength to make it short or long -

Fluttertoast.showToast(
        msg: "This is Center Short Toast",
        toastLength: Toast.LENGTH_SHORT,
    );

Hope this helps. Let me know.

  • Related