use platformView and endRecording().toImage() Crash

This issue has been tracked since 2022-11-25.

#113677

main.dart

import 'dart:ui' as ui;

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

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Demo Home Page'),
      ),
      body: tagView(),
      floatingActionButton: const FloatingActionButton(
        onPressed: zoomPoiMark,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  tagView() {
    return const UiKitView(
        viewType: "platform_text_view",
        creationParams: <String, dynamic>{"text": "iOS"},
        creationParamsCodec: StandardMessageCodec());
  }
}

zoomPoiMark() async {
  final recorder = ui.PictureRecorder();
  final canvas = Canvas(recorder);
  final paint = Paint()..color = Colors.black.withOpacity(0.6);

  canvas.drawRRect(
      RRect.fromLTRBR(0, 0, 1, 1, const Radius.circular(1)), paint);

  final path = Path();
  canvas.drawPath(path, paint);

  await recorder.endRecording().toImage(1, 1);
}

AppDelegate.swift

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      let factory = PlatformTextViewFactory()
          let registrar = self.registrar(forPlugin: "platform_text_view_plugin")
      registrar?.register(factory, withId: "platform_text_view")
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

class PlatformTextViewFactory: NSObject,FlutterPlatformViewFactory {
    func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
        return PlatformTextView(frame,viewID: viewId,args: args)
    }
    func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
        return FlutterStandardMessageCodec.sharedInstance()
    }
}

class PlatformTextView: NSObject,FlutterPlatformView {
    let frame: CGRect;
    let viewId: Int64;
    var text:String = ""

    init(_ frame: CGRect,viewID: Int64,args :Any?) {
        self.frame = frame
        self.viewId = viewID
        if(args is NSDictionary){
            let dict = args as! NSDictionary
            self.text = dict.value(forKey: "text") as! String
        }
    }
    func view() -> UIView {
        let label = UILabel()
        label.text = self.text
        label.textColor = UIColor.red
        label.frame = self.frame
        return label
    }
}

flutter doctor -v

[✓] Flutter (Channel stable, 3.3.2, on macOS 12.6 21G115 darwin-x64, locale zh-Hans-CN)
    • Flutter version 3.3.2 on channel stable at /Users/ctrip/Development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision e3c29ec00c (3 months ago), 2022-09-14 08:46:55 -0500
    • Engine revision a4ff2c53d8
    • Dart version 2.18.1
    • DevTools version 2.15.0
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/ctrip/Library/Android/sdk
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[!] Xcode - develop for iOS and macOS (Xcode 14.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14A400
    ! CocoaPods 1.10.1 out of date (1.11.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#installation for instructions.

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

[✓] Android Studio (version 4.1)
    • 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
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • iPhone 14 Pro (mobile) • A7725915-3455-4399-B6BE-B73BA6FA0AE9 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-0 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     • macOS 12.6 21G115 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 107.0.5304.121
    ! Error: To use Jarmon 12 for development, enable Developer Mode in Settings → Privacy & Security.  (code 6)

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 2 categories.

log

2022-11-30 10:35:56.494718+0800 Runner[9790:60341] [VERBOSE-2:thread_checker.h(61)] IsCreationThreadCurrent expected thread: 'io.flutter.1.raster' actual thread:''
2022-11-30 10:35:56.494896+0800 Runner[9790:60341] [VERBOSE-3:weak_ptr.h(111)] Check failed: (checker_.checker).IsCreationThreadCurrent().
CoreSimulator 857.7 - Device: iPhone 14 Pro (A7725915-3455-4399-B6BE-B73BA6FA0AE9) - Runtime: iOS 16.0 (20A360) - DeviceType: iPhone 14 Pro
zhanfengkuang wrote this answer on 2022-11-25

click increment button will be crash

exaby73 wrote this answer on 2022-11-25

Hello @zhanfengkuang. The code you provided seems too long and complex. Could you reduce the code to follow complete and minimal, reproducible example so that I may verify it?

Please also include the logs of flutter doctor -v and flutter run -v

zhanfengkuang wrote this answer on 2022-11-30

我猜测该问题是由于 使用了platformView组件,Platform线程与Raster线程合并,当调用toImage()方法,Rasterizer对象是在Raster线程初始化,在Platform线程调用时弱引用指针检查线程安全导致的KillProcess()。

Translated via Google Translate

I guess this problem is due to the use of the platformView component, the merge of the Platform thread and the Raster thread, when the toImage() method is called, the Rasterizer object is initialized on the Raster thread, and the weak reference pointer is checked for thread safety when the Platform thread calls KillProcess().

huycozy wrote this answer on 2022-11-30

@zhanfengkuang Please provide the information indicated at #116005 (comment) so that we may verify the issue better.

More Details About Repo
Owner Name flutter
Repo Name flutter
Full Name flutter/flutter
Language Dart
Created Date 2015-03-06
Updated Date 2022-12-07
Star Count 147031
Watcher Count 3560
Fork Count 23915
Issue Count 11300

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date