我创建了一个Flutter应用并使用了Getx包。但是当我尝试使用它来显示snack bar时,该函数被执行但是snack bar没有出现。
onPressed: () {
print("executed");
Get.snackbar(
"title",
"content",
);
},
我创建了一个Flutter应用并使用了Getx包。但是当我尝试使用它来显示snack bar时,该函数被执行但是snack bar没有出现。
onPressed: () {
print("executed");
Get.snackbar(
"title",
"content",
);
},
将 MaterialApp() widget 更改为 GetMaterialApp() widget。
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);
你需要将MaterialApp()小部件更改为GetMaterialApp()小部件。
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)),
),
),
),
);
}
}