Display SnackBar in Flutter

前端 未结 15 1517
一个人的身影
一个人的身影 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();
      
      @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'),
              ),
            ),
          ),
        );
      }
      

提交回复
热议问题