Flutter update UI from native method call by using setState() method
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));
}
}
Comments
-
J. Hegg over 1 year
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 aFuture
. But here comes the problem, I want to update my UI when the native code invokes the callback, so I want to use thesetState()
methode. The problem now is, thatsetState()
doesn't allow to be called within a async function e.g. a function that returns aFuture
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.