1
votes

I am invoking a method from native Android code by using the platform channel like this:

MethodChannel(flutterView, CHANNEL).invokeMethod(METHOD_NAME, null)

in my Flutter class I handle the respective method call by using a callback platform.setMethodCallHandler(_handleNativeMethodCall)

The setMethodCallHandler() requires the callback to return a Future. But here comes the problem, I want to update my UI when the native code invokes the callback, so I want to use the setState() methode. The problem now is, that setState() doesn't allow to be called within a async function e.g. a function that returns a Future and therefore not in the callback for the native method invocation.

Does anyone of you faced this problem and may got a solution for this? It would be ridiculous if updating the UI from this callback wouldn't be possible.

1

1 Answers

1
votes

You can register any method as the method call callback and call setState from there.


class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  String myVariable;

  @override
  initState() {
    super.initState();
    myVariable = 'LOADING';
    platform.setMethodCallHandler(_handleNativeMethodCall);
  }

  Future<dynamic> _handleNativeMethodCall(MethodCall methodCall) async {
    // do some processing
    setState(() {
      myVariable = methodCall.method;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: Text(myVariable));
  }
}