如何在Flutter中创建和使用SnackBar进行重复使用(全局) [英] how to Create and Use SnackBar for ReUse(Globally) in Flutter
本文介绍了如何在Flutter中创建和使用SnackBar进行重复使用(全局)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要为可重复使用(全局)创建SnackBar
i want create SnackBar
for reusable(globally)
我已经创建了,但是只有一页,我不知道如何创建可重用.
i already created but its only for 1 page , i don't know how to create reusable.
以下代码:
import 'package:flutter/material.dart';
class SnackBarMain extends StatefulWidget {
@override
_SnackBarMainState createState() => _SnackBarMainState();
}
class _SnackBarMainState extends State<SnackBarMain> {
final globalKey = GlobalKey<ScaffoldState>();
String title = 'SnackBar';
@override
Widget build(BuildContext context) {
return Scaffold(
key: globalKey,
resizeToAvoidBottomPadding: false,
appBar: AppBar(
centerTitle: true,
title: Text(title),
),
body: Center(
child: RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.purple)),
onPressed: () => snackBarMsg(context),
color: Colors.purple,
textColor: Colors.white,
child: Text("SnackBar",
style: TextStyle(fontSize: 18)),
),
),
);
}
snackBarMsg(BuildContext context) {
final sb = SnackBar(
elevation: 0.0,
//behavior: SnackBarBehavior.floating,
content: Text('SnackBar Bottom Message'),
duration: new Duration(seconds: 5000000),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
),
//backgroundColor: Colors.redAccent,
action: SnackBarAction(
textColor: Color(0xFFFAF2FB),
label: 'OK',
onPressed: () {},
),
);
globalKey.currentState.showSnackBar(sb);
}
}
所以任何人都可以给我举个例子
so any one please give me example for this
推荐答案
只需创建一个公共类并将自定义函数放入其中,例如:
Just create a public class and put your custom functions inside, here you go for example:
//Custom class in project directory
class CustomWidgets {
CustomWidgets._();
static buildErrorSnackbar(BuildContext context, String message) {
Scaffold.of(context)
.showSnackBar(
SnackBar(
content: Text("$message"),
),
);
}
}
// This is any page in your project
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
// Always create body with Builder method so you can
// get exact context to pass
body: Builder(
builder: (context) =>
Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: (){
CustomWidgets.buildErrorSnackbar(context,"Your message here");
},
child: Text('Display SnackBar'),
),
),
),
);
}
}
这篇关于如何在Flutter中创建和使用SnackBar进行重复使用(全局)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文