illrune
illrune

Reputation: 1

Problem using setState in Flutter event channel listener

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) {
        ...
      });
  }
}

Upvotes: -1

Views: 77

Answers (1)

Vivek Chib
Vivek Chib

Reputation: 1846

  @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) {
      ...
    });
  }

Upvotes: 0

Related Questions