Display SnackBar in Flutter

前端 未结 15 1339
一个人的身影
一个人的身影 2020-12-04 19:28

I want to display a simple SnackBar inside Flutter\'s stateful widget. My application creates new instance of MaterialApp with a stateful widget ca

相关标签:
15条回答
  • 2020-12-04 20:05

    ScaffoldState is now deprecated. Use ScaffoldMessengerState.

    There are generally two ways of showing the SnackBar using ScaffoldMessenger.


    1. Direct way:

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: RaisedButton(
            onPressed: () {
              var snackBar = SnackBar(content: Text('Hello World'));
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            },
            child: Text('Show SnackBar'),
          ),
        );
      }
      

    1. Using GlobalKey.

      final _globalKey = GlobalKey<ScaffoldMessengerState>();
      
      @override
      Widget build(BuildContext context) {
        return ScaffoldMessenger(
          key: _globalKey,
          child: Scaffold(
            body: Center(
              child: RaisedButton(
                onPressed: () {
                  var snackBar = SnackBar(content: Text('Hello World'));
                  _globalKey.currentState.showSnackBar(snackBar);
                },
                child: Text('Show SnackBar'),
              ),
            ),
          ),
        );
      }
      
    0 讨论(0)
  • 2020-12-04 20:05

    **

    ScaffoldState is now deprecated. Use ScaffoldMessengerState.

    **

    All the above solutions are amazing but as it's deprecated now you should use it this way.

        var snackBar = SnackBar(content: Text('Hello World'));
    
        ScaffoldMessenger.of(_scaffoldKey.currentContext)
        .showSnackBar(snackBar );
    
    0 讨论(0)
  • 2020-12-04 20:07

    To initialise a Snackbar on initState() you can execute a function after the layout is built.

    void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Your message here..")));}
    
    0 讨论(0)
提交回复
热议问题