Problem using setState in Flutter event channel listener

50 views Asked by At

I am using a translator. Please understand. I am using EventChannel to receive messages from Android to Flutter. The eventChannel listener works, but I can't use setState or snackbar inside it. print() works inside the listener. However, if you use setState and snackBar, there is no change. There are no errors.

Using _key.currentContext(_key registered in build-Scaffold) instead of context also fails. Using WidgetsBinding.instance.addPostFrameCallback is the same.

I hope someone can help me...

class _MyPageState extends State<MyPage> {
  static const eventChannel = EventChannel('com.example.my_app/event');
  final GlobalKey<ScaffoldState> _key = GlobalKey();
  StreamSubscription<dynamic>? _eventSubscription;
  bool onSuccess = false;

  @override
  void initState() {
    super.initState();
    _eventSubscription = eventChannel.receiveBroadcastStream().listen((data) {
        // success
        ScaffoldMessenger.of(context).showSnackBar(  // _key.currentContext also does not work
          const SnackBar(content: Text('success')),
        );
        setState(() { onSuccess = true });
        // onSuccess = true;
      }, onError: (error) {
        ...
      });
  }
}
1

There are 1 answers

1
Vivek Chib On
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) => eventSubscription());
  }

  void eventSubscription(){
    _eventSubscription = eventChannel.receiveBroadcastStream().listen((data) {
      // success
      ScaffoldMessenger.of(context).showSnackBar(  
        const SnackBar(content: Text('success')),
      );
      setState(() { onSuccess = true });
      // onSuccess = true;
    }, onError: (error) {
      ...
    });
  }