首页 > 解决方案 > 如何将 Native java 中的变量值获取到 Flutter?

问题描述

我的应用程序从蓝牙接收数据,并将其存储在 Java(本机)中的变量中。我可以在 toast 消息中显示。需要将值移动到颤振我必须在 initstate 中显示颤振中的值。谁能帮我?我的处理程序。

handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg){
                if(msg.what == MESSAGE_READ){
                     readMessage = null;
                    try {
                        readMessage = new String((byte[]) msg.obj, "UTF-8");
                                               

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                   Toast.makeText(getApplicationContext(),"MEssage"+readMessage,Toast.LENGTH_LONG).show();

                }

                if(msg.what == CONNECTION_STATUS){
                    if(msg.arg1 == 1)
                    {
                        bluetoothStatus=true;
                        result.success(bluetoothStatus);
                    }

                    else
                    {
                        bluetoothStatus=false;
                        result.success(bluetoothStatus);

                    }

                }
            }
        };

标签: javaandroidflutternative

解决方案


官方文档中有一个方法可以做到这一点(https://flutter.dev/docs/development/platform-integration/platform-channels)基本上你需要用Java编写一个方法并在Flutter中按名称调用它;因为它将是异步的,您可能会使用这样的 FutureBuilder

 class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final Future<String> _calculation = Future<String>.delayed(
    const Duration(seconds: 2),
    () => 'Data Loaded',
  );

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: Theme.of(context).textTheme.headline2!,
      textAlign: TextAlign.center,
      child: FutureBuilder<String>(
        future: _calculation, 
     .........

推荐阅读