samuelezedi / flutter_clipboard

A plugin that helps you copy to clipboard and paste from clipboard.
Other
36 stars 7 forks source link

Not worked in another isolate :( #9

Closed TENX-S closed 2 years ago

TENX-S commented 3 years ago
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:clipboard/clipboard.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String content = 'waiting';

  late Isolate _notify;
  late ReceivePort _notifyPort;

  void _startNotify() async {
    _notifyPort = ReceivePort();
    _notify = await Isolate.spawn(_watchClipboard, _notifyPort.sendPort);
    _notifyPort.listen(_handleClipboard);
  }

  static void _watchClipboard(SendPort sendPort) async {
    sendPort.send(await FlutterClipboard.paste());
  }

  void _handleClipboard(dynamic clipContent) {
    setState(() {
      content = clipContent;
    });
  }

  void _stopNotify() {
    _notifyPort.close();
    _notify.kill(priority: Isolate.immediate);
  }

  @override
  void initState() {
    super.initState();
    _startNotify();
  }

  @override
  void dispose() {
    super.dispose();
    _stopNotify();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(content),
    );
  }
}

stderr:

[ERROR:flutter/runtime/dart_isolate.cc(1137)] Unhandled exception:
Null check operator used on a null value
#0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
#2      OptionalMethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:461:18)
#3      Clipboard.getData (package:flutter/src/services/clipboard.dart:54:72)
#4      FlutterClipboard.paste (package:clipboard/clipboard.dart:20:43)
#5      _HomePageState._watchClipboard (package:paste_demo/main.dart:37:42)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:286:17)
#7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)