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

Viewed 808

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) => {}
);
2 Answers

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