Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled Exception: Binding has not yet been initialized - when running Isolate sample example #145873

Closed
shashkiranr opened this issue Mar 28, 2024 · 5 comments
Labels
engine flutter/engine repository. See also e: labels. found in release: 3.19 Found to occur in 3.19 found in release: 3.21 Found to occur in 3.21 has reproducible steps The issue has been confirmed reproducible and is ready to work on r: solved Issue is closed as solved team-engine Owned by Engine team

Comments

@shashkiranr
Copy link

shashkiranr commented Mar 28, 2024

Steps to reproduce

Run the Isolate example

import 'dart:convert';
import 'dart:isolate';

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

const filename = 'json_01.json';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final jsonData = await Isolate.run(() => _readAndParseJson(filename));
  print('Number of JSON keys: ${jsonData.length}');
  runApp(const MyApp());
}

/// Reads the contents of the file with [filename],
/// decodes the JSON, and returns the result.
Future<Map<String, dynamic>> _readAndParseJson(String filename) async {
  final fileData = await rootBundle.loadString('assets/$filename');
  final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
  return jsonData;
}

json_01.json

{
  "a": "foo"
}

tried to replace await Isolate.run(() => _readAndParseJson(filename)) with await compute(_readAndParseJson, filename) and getting the same error

Expected results

Number of JSON keys: 1

Actual results

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Binding has not yet been initialized.
The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.
#0      BindingBase.checkInstance.<anonymous closure> (pac<…>

Code sample

Code sample
[Paste your code here]

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.19.4, on macOS 14.3 23D56 darwin-arm64, locale en-IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[!] Xcode - develop for iOS and macOS (Xcode 15.2)
    ! CocoaPods 1.11.3 out of date (1.13.0 is recommended).
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To upgrade see https://guides.cocoapods.org/using/getting-started.html#updating-cocoapods for instructions.
[✓] Chrome - develop for the web
[✓] Android Studio (version 2023.2)
[✓] IntelliJ IDEA Ultimate Edition (version 2023.2.4)
[✓] VS Code (version 1.82.2)
[✓] Connected device (4 available)
[✓] Network resources
@huycozy huycozy added the in triage Presently being triaged by the triage team label Mar 28, 2024
@huycozy
Copy link
Member

huycozy commented Mar 28, 2024

Hi @shashkiranr
I think you are hitting a similar issue at #130570 that calls platform channel in isolate, please see:

class PlatformAssetBundle extends CachingAssetBundle {
@override
Future<ByteData> load(String key) {
final Uint8List encoded = utf8.encode(Uri(path: Uri.encodeFull(key)).path);
final Future<ByteData>? future = ServicesBinding.instance.defaultBinaryMessenger.send(
'flutter/assets',

It's marked as a duplicate of #119207. So I'm going to close the issue in favor of this one. Please follow up on it for updates.

@huycozy huycozy closed this as not planned Won't fix, can't repro, duplicate, stale Mar 28, 2024
@huycozy huycozy added r: duplicate Issue is closed as a duplicate of an existing issue and removed in triage Presently being triaged by the triage team labels Mar 28, 2024
@shashkiranr
Copy link
Author

I am not using any Platform Channels. Its a basic example of running Isolates from the main function. So you are telling me I can't run the sample isolate example?

@huycozy
Copy link
Member

huycozy commented Mar 28, 2024

I am not using any Platform Channels.

The rootBundle does, that's why I quoted the code above. The defaultBinaryMessenger will send a binary message to the platform plugins on the given channel:

/// Send a binary message to the platform plugins on the given channel.
///
/// Returns a [Future] which completes to the received response, undecoded,
/// in binary form.
Future<ByteData?>? send(String channel, ByteData? message);

You can compare this with a different process like in the sample code below which does I/O task (write to file), the isolate works as expected in this case but reading assets task does not.

Sample code
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // final jsonData = await Isolate.run(() => _readAndParseJson(filename));
  // print('Number of JSON keys: ${jsonData.length}');
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      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> {
  int usingTime = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Running time: $usingTime ms"),
            TextButton(onPressed: _runWithIsolate, child: const Text("Run with isolate")),
            TextButton(
                onPressed: _runWithIsolateInPlatformChannel,
                child: const Text("Run with isolate in platform channel")),
          ],
        ),
      ),
    );
  }

  void _runWithIsolate() async {
    var savePath = await getTemporaryDirectory();
    var duration = await compute((path) => _runTask(path), "${savePath.path}/test.log");
    print('With isolate duration: $duration');
    if (mounted) {
      setState(() {
        usingTime = duration;
      });
    }
  }

  static int _runTask(String savePath) {
    var file = File(savePath);
    if (file.existsSync()) {
      file.deleteSync();
    }
    file = File(savePath);
    var startTime = DateTime.now().millisecondsSinceEpoch;
    for (var i = 0; i < 100; i++) {
      file.writeAsStringSync("a\n", mode: FileMode.append);
    }
    return DateTime.now().millisecondsSinceEpoch - startTime;
  }

  void _runWithIsolateInPlatformChannel() async {
    // final jsonData = await Isolate.run(() => _readAndParseJson(filename));
    // print('Number of JSON keys: ${jsonData.length}');
    final jsonData = await compute(_readAndParseJson, 'json_01.json');
    print('Number of JSON keys: ${jsonData}');
  }

  /// Reads the contents of the file with [filename],
  /// decodes the JSON, and returns the result.
  static Future<int> _readAndParseJson(String filename) async {
    final fileData = await rootBundle.loadString('assets/$filename');
    final jsonData = jsonDecode(fileData) as Map<String, String>;
    return jsonData.length;
  }
}

However, when I check the sample code on https://docs.flutter.dev/perf/isolates which also loads assets in isolate, it seems to have worked before. I will re-open this for further insights. The issue is reproduced in the latest Flutter master channel.

flutter doctor -v (stable and master)
[✓] Flutter (Channel stable, 3.19.4, on macOS 14.1 23B74 darwin-x64, locale en-VN)
    • Flutter version 3.19.4 on channel stable at /Users/huynq/Documents/GitHub/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 68bfaea224 (29 hours ago), 2024-03-20 15:36:31 -0700
    • Engine revision a5c24f538d
    • Dart version 3.3.2
    • DevTools version 2.31.1

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/huynq/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/huynq/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15C500b
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • android-studio-dir = /Applications/Android Studio.app/
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)

[✓] VS Code (version 1.87.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.84.0

[✓] Connected device (3 available)
    • RMX2001 (mobile) • EUYTFEUSQSRGDA6D • android-arm64  • Android 11 (API 30)
    • macOS (desktop)  • macos            • darwin-x64     • macOS 14.1 23B74 darwin-x64
    • Chrome (web)     • chrome           • web-javascript • Google Chrome 123.0.6312.58

[✓] Network resources
    • All expected network resources are available.

• No issues found!
[!] Flutter (Channel master, 3.21.0-16.0.pre.14, on macOS 14.1 23B74 darwin-x64, locale en-VN)
    • Flutter version 3.21.0-16.0.pre.14 on channel master at /Users/huynq/Documents/GitHub/flutter_master
    ! Warning: `flutter` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
    ! Warning: `dart` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision f5b65bad0f (2 hours ago), 2024-03-27 18:20:55 -0700
    • Engine revision c602abdbae
    • Dart version 3.4.0 (build 3.4.0-279.0.dev)
    • DevTools version 2.34.0-dev.12
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/huynq/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • ANDROID_HOME = /Users/huynq/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15C500b
    • CocoaPods version 1.15.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • android-studio-dir = /Applications/Android Studio.app/
    • Java version OpenJDK Runtime Environment (build 17.0.9+0-17.0.9b1087.7-11185874)

[✓] VS Code (version 1.87.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.84.0

[✓] Connected device (3 available)
    • RMX2001 (mobile) • EUYTFEUSQSRGDA6D • android-arm64  • Android 11 (API 30)
    • macOS (desktop)  • macos            • darwin-x64     • macOS 14.1 23B74 darwin-x64
    • Chrome (web)     • chrome           • web-javascript • Google Chrome 123.0.6312.86

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

@huycozy huycozy reopened this Mar 28, 2024
@huycozy huycozy added engine flutter/engine repository. See also e: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on team-engine Owned by Engine team found in release: 3.19 Found to occur in 3.19 found in release: 3.21 Found to occur in 3.21 and removed r: duplicate Issue is closed as a duplicate of an existing issue labels Mar 28, 2024
@jonahwilliams
Copy link
Member

The sample code loads the string outside of the isolate and passes it in. There should be no copies with strings, so that should work ok.

Closing as this is not a bug or regression.

@huycozy huycozy added the r: solved Issue is closed as solved label Apr 2, 2024
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 16, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
engine flutter/engine repository. See also e: labels. found in release: 3.19 Found to occur in 3.19 found in release: 3.21 Found to occur in 3.21 has reproducible steps The issue has been confirmed reproducible and is ready to work on r: solved Issue is closed as solved team-engine Owned by Engine team
Projects
None yet
Development

No branches or pull requests

3 participants