Flutter Getx Snackbar不工作

9

我创建了一个Flutter应用并使用了Getx包。但是当我尝试使用它来显示snack bar时,该函数被执行但是snack bar没有出现。

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

19

将 MaterialApp() widget 更改为 GetMaterialApp() widget。


2
要使用GetX Snack Bar,您必须在main.dart中使用GetMaterialApp而不是MaterialApp
您也可以创建自定义的SnackBar

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 }

现在你可以在任何地方以这种方式使用它。

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

2

你需要将MaterialApp()小部件更改为GetMaterialApp()小部件。


2
唯一的原因是您在开始时没有使用GetMaterialApp()小部件。

0
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)),
          ),
        ),
      ),
    );
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接