Giter VIP home page Giter VIP logo

Comments (4)

jonahwilliams avatar jonahwilliams commented on June 23, 2024 1

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.

from flutter.

huycozy avatar huycozy commented on June 23, 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.

from flutter.

shashkiranr avatar shashkiranr commented on June 23, 2024

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?

from flutter.

huycozy avatar huycozy commented on June 23, 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.

from flutter.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.