android Flutter隔离:在执行BackgroundIsolateBinaryMessenger.ensureInitialized之前,BackgroundIsolateBinaryMessenger.instance值无效

nwo49xxi  于 2023-04-18  发布在  Android
关注(0)|答案(1)|浏览(907)

在Android API28模拟器上运行的Flutter应用程序上,启动Isolate将导致应用程序崩溃并显示错误:
[Bad state:在执行BackgroundIsolateBinaryMessenger.ensureInitialized之前,BackgroundIsolateBinaryMessenger.instance值无效。,#0 BackgroundIsolateBinaryMessenger.instance
我已经在运行runApp(const MyApp());之前运行WidgetsFlutterBinding.ensureInitialized();,这应该可以确保在应用程序开始运行之前已经初始化了BackgroundIsolateBinaryMessenger
我们还需要运行BackgroundIsolateBinaryMessenger.ensureInitialized吗?我们该怎么做?

import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sensors_plus/sensors_plus.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _x = 0;

  static void _isolateTask(SendPort sendPort) async {
    debugPrint("Inside _isolateTask");

    accelerometerEvents.listen((AccelerometerEvent event) {
      debugPrint('_isolateTask x: $event.x');
      sendPort.send(event.x);
    });
  }

  void _startIsolate() async {
    debugPrint("_startIsolate()");

    var receivePort = ReceivePort();

    await Isolate.spawn(_isolateTask, receivePort.sendPort);

    receivePort.listen((dynamic message) {
      setState(() {
        _x = message;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'X: $_x',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _startIsolate,
        tooltip: 'Start Isolate',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

全程跟踪

I/flutter ( 5071): _startIsolate()
I/flutter ( 5071): Inside _isolateTask
I/flutter ( 5071): error: [Bad state: The BackgroundIsolateBinaryMessenger.instance value is invalid until BackgroundIsolateBinaryMessenger.ensureInitialized is executed., #0      BackgroundIsolateBinaryMessenger.instance
_background_isolate_binary_messenger_io.dart:27
I/flutter ( 5071): #1      _findBinaryMessenger
platform_channel.dart:135
I/flutter ( 5071): #2      EventChannel.binaryMessenger
platform_channel.dart:629
I/flutter ( 5071): #3      EventChannel.receiveBroadcastStream.<anonymous closure>
platform_channel.dart:649
I/flutter ( 5071): #4      _runGuarded (dart:async/stream_controller.dart:814:24)
I/flutter ( 5071): #5      _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:207:7)
I/flutter ( 5071): #6      _ControllerStream._createSubscription (dart:async/stream_controller.dart:827:19)
I/flutter ( 5071): #7      _StreamImpl.listen (dart:async/stream_impl.dart:471:9)
I/flutter ( 5071): #8      new _ForwardingStreamSubscription (dart:async/stream_pipe.dart:114:10)
I/flutter ( 5071): #9      _ForwardingStream._createSubscription (dart:async/stream_pipe.dart:86:16)
I/flutter ( 5071): #10     _ForwardingStream.listen (dart:async/stream_pipe.dart:81:12)
I/flutter ( 5071): #11     _MyHomePageState._isolateTask
main.dart:44
I/flutter ( 5071): #12     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:17)
I/flutter ( 5071): #13     _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)
I/flutter ( 5071): ]

依赖关系

dependencies:
    flutter:
      sdk: flutter
    wear: ^1.1.0
    sensors_plus: ^2.0.2
bjp0bcyl

bjp0bcyl1#

添加BackgroundIsolateBinaryMessenger.ensureInitialized at top of isolate.

RootIsolateToken rootIsolateToken = RootIsolateToken.instance!;
  void _isolateTask(SendPort sendPort) async {
    debugPrint("Inside _isolateTask");
    BackgroundIsolateBinaryMessenger.
    ensureInitialized(rootIsolateToken);
    accelerometerEvents.listen((AccelerometerEvent event) {
      debugPrint('_isolateTask x: $event.x');
      sendPort.send(event.x);
    });
  }

相关问题