如何在 Flutter 中创建和使用 SnackBar 以进行重用(全局)

MD *_*ali 6 snackbar flutter

我想创建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);
  }
}
Run Code Online (Sandbox Code Playgroud)

所以任何人请给我举个例子

Seb*_*ian 8

您可以拥有一个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: () {},
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 是啊伙计!非常感谢,这正是我所需要的 (2认同)

Mat*_*een 8

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

//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'),
          ),
         ),
     ),
  );
 }
}
Run Code Online (Sandbox Code Playgroud)