How to show a SnackBar in callback onEvent of EventChannel.listen

烂漫一生 提交于 2021-01-02 20:31:53

问题


An event is received from native code using EventChannel.

Content is String, and I'd like to show it with SnackBar.

But Scaffold.of returns null. And I found nothing to get BuildContext of Scaffold created by Widget Build(...).

The code is like this:

@override
void initState() {
super.initState();

showMsg.receiveBroadcastStream().listen(
    (event) => setState(() {
        Scaffold.of(context).showSnackBar(new SnackBar(
            content: new Text(event.toString()),
        ));
    }),
    onError: (event) => {}
);

回答1:


EDIT / UPDATED ANSWER

With the new Flutter update you now have to use ScaffoldMessenger to show the SnackBar.

ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('test'),
        ),
      );

I am using below Flutter version and channel

1.24.0-10.1.pre • channel dev •

OLD ANSWER

You will need a key for the Scaffold using which you can get the state of the Scaffold

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Now in your build method, it must return the scaffold. in the Scaffold assign the key: _scaffoldKey,

return new Scaffold(
      key: _scaffoldKey,
      ...,
);

using this key you can access the state of the Scaffold.

_scaffoldKey.currentState.showSnackBar(new SnackBar(
            content: new Text(event.toString()),
));



回答2:


import 'package:flutter/material.dart';

void main() => runApp(SnackBarExample());

class SnackBarExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SnackBar Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('SnackBar Example'),
        ),
        body: SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: Text('This is a SnackBar!'),
            action: SnackBarAction(
              label: 'Action',
              onPressed: () {
                // Some code to action.
              },
            ),
          );

          Scaffold.of(context).showSnackBar(snackBar);
        },
        child: Text('Showing SnackBar'),
      ),
    );
  }
}


来源:https://stackoverflow.com/questions/52308087/how-to-show-a-snackbar-in-callback-onevent-of-eventchannel-listen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!