skip to Main Content

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

2

Answers


  1.   @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) {
          ...
        });
      }
    
    Login or Signup to reply.
  2. You have a syntax error in your code. You forgot a semicolon.

    setState(() { onSuccess = true });
    

    needs to be

    setState(() { onSuccess = true; });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search