Flutter Getx Snackbar not wroking

Viewed 8406

I have created a flutter app and used getx package. But then I used it to show the snack bar, the function gets executed but the snack bar is not showing up.

 onPressed: () {
        print("executed");
        Get.snackbar(
            "title",
            "content",
          ); 
        },
5 Answers

Change the MaterialApp() widget to GetMaterialApp() widget.

The only reason is you are not using GetMaterialApp() widget in the starting.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Center(
            child: ElevatedButton(
                onPressed: () {
                  print("executed");
                  Get.snackbar(
                    "title",
                    "content",
                  );
                },
                child: Icon(Icons.ac_unit)),
          ),
        ),
      ),
    );
  }
}

you have to change the MaterialApp() widget to GetMaterialApp() widget.

To use GetX Snack Bar you must use GetMaterialApp instead of MaterialApp in main.dart.

You can create your custom SnackBar also.


final kPadding = 8.0; // up to you
 
class Snack {
  /// show the snack bar
  /// [content] is responsible for the text of the snack bar
  static show({
    required String content,
    SnackType snackType = SnackType.info,
    SnackBarBehavior behavior = SnackBarBehavior.fixed,
  }) {
    ScaffoldMessenger.of(Get.context!).showSnackBar(
      SnackBar(
        content: Text(
          content,
          style: Get.textTheme.headline5
              ?.copyWith(color: _getSnackbarTextColor(snackType)),
        ),
        behavior: behavior,
        backgroundColor: _getSnackbarColor(snackType),
        padding: const EdgeInsets.symmetric(
          horizontal: kPadding * 3,
          vertical: kPadding * 2,
        ),
      ),
    );
  }

  static Color _getSnackbarColor(SnackType type) {
    if (type == SnackType.error) return const Color(0xffFF7A7A);
    if (type == SnackType.warning) return Colors.amber;
    if (type == SnackType.info) return Colors.blue;
    return Colors.white;
  }

  static Color _getSnackbarTextColor(SnackType type) {
    if (type == SnackType.error || type == SnackType.info) return Colors.white;

    return const Color(0xff1C1C1C);
  }
}

enum SnackType { info, warning, error }

Now anywhere you can use this in this way.

Snack.show(content: 'Your Snack Message', snackType: SnackType.error, behavior: SnackBarBehavior.floating);
Related