【问题标题】:how to Create and Use SnackBar for ReUse(Globally) in Flutter如何在 Flutter 中创建和使用 SnackBar 进行重用(全局)
【发布时间】:2020-06-04 17:26:08
【问题描述】:

我想创建SnackBar 用于可重用(全局)

我已经创建了,但它只适用于 1 页,我不知道如何创建可重复使用的

以下代码:

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

所以任何人都请给我这个例子

【问题讨论】:

  • snackBar 是否会在整个应用程序中显示相同的消息?你希望它可以在全球范围内访问。
  • 不,我想在整个应用程序中显示不同的消息,并且我希望全局访问

标签: flutter snackbar


【解决方案1】:

只需创建一个公共类并将您的自定义函数放入其中,例如:

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

【讨论】:

    【解决方案2】:

    你可以有一个class,它有一个静态方法show(),它接收context并显示一个snackbar。 检查下面的代码。

    class GlobalSnackBar {
      final String message;
    
      const GlobalSnackBar({
        @required this.message,
      });
    
      static show(
        BuildContext context,
        String message,
      ) {
        Scaffold.of(context).showSnackBar(
          SnackBar(
            elevation: 0.0,
            //behavior: SnackBarBehavior.floating,
            content: Text(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: () {},
            ),
          ),
        );
      }
    }
    

    你可以像这样从任何地方调用它:

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return RaisedButton(
          child: Text('SHOW Snackbar'),
          onPressed: () => GlobalSnackBar.show(context, 'Test'),
        );
      }
    }
    

    请记住,您传递给show() 方法的context 必须是Scaffold 的后代,才能显示SnackBar

    【讨论】:

      【解决方案3】:

      Scaffold.of(context).showSnackbar 现已弃用。您应该改用 ScaffoldMessenger。像这样使用:-

      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text('User Successfully Logged In...'),
              ));
      

      【讨论】:

      • 你的意思是 Scaffold.of(context).showSnackbar(snackbar)... 已弃用。
      • @ReinierGarcia 是的,现在已弃用。
      • 你还不明白。不推荐使用的是 Scaffold.of(context).showSnackbar。不是 SnackBar.showSnackbar。您实际上是在说:“SnackBar.showSnackbar 现在已弃用......”这是不正确的。
      • @ReinierGarcia 是的,你是真的。感谢您纠正我。
      【解决方案4】:

      您可以使用您已经定义的Snackbar 将它放在一个公共文件夹中,以便在任何地方重复使用它,该文件夹可以从您应用中的任何位置访问。您不需要将它包含在小部件或类中。然后,您可以通过调用Scaffold.of(context).showSnackBar(...) 来展示它。为此,您当然需要传递当前的BuildContext。这样,只要您调用showSnackBarcontext 有父Scaffold,就会为您的当前页面显示小吃栏,您可以在任何地方执行此操作。

      考虑一下我自己过去使用过的这个例子:

        void buildErrorSnackbar(BuildContext context) {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content: Text("Oops! Something went wrong."),
            ),
          );
        }
      

      【讨论】:

      • 兄弟如何在另一个页面调用snackbar?
      • 你可以在任何地方声明你自己的buildSnackbar方法,你不需要将它包含在一个类中。这样就可以在任何地方调用,只需要传递对应的BuildContext即可。
      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 2022-08-08
      • 2021-03-23
      • 2020-01-12
      • 2020-09-29
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多