简体   繁体   中英

Flutter update UI from native method call by using setState() method

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 eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM