Flutter can't read from Clipboard

前端 未结 4 1324
耶瑟儿~
耶瑟儿~ 2021-01-07 07:52

I come asking for quite a specific question regarding Flutter and the Future and await mechanism, which seems to be working, but my Clipboard does not really function while

相关标签:
4条回答
  • 2021-01-07 08:33

    It's works for me:

      _getFromClipboard() async {
        Map<String, dynamic> result =
            await SystemChannels.platform.invokeMethod('Clipboard.getData');
        if (result != null) {
          return result['text'].toString();
        }
        return '';
      }
    
    0 讨论(0)
  • 2021-01-07 08:36

    First create a method

    Future<String> getClipBoardData() async {
            ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
            return data.text;
          }
    

    Then in build method

    FutureBuilder(
                    future: getClipBoardData(),
                    initialData: 'nothing',
                    builder: (context, snapShot){
                      return Text(snapShot.data.toString());
                    },
                  ),
    
    0 讨论(0)
  • 2021-01-07 08:38

    You can simply re-use Flutter's existing library code to getData from Clipboard.

    ClipboardData data = await Clipboard.getData('text/plain');
    
    0 讨论(0)
  • 2021-01-07 08:46

    Also can be useful if you want to listen for periodic updates from the system clipboard. Originally I replied here, just re-posting the solution:

    #creating a listening Stream:
    final clipboardContentStream = StreamController<String>.broadcast();
    
    #creating a timer for updates:
    Timer clipboardTriggerTime;
    
    clipboardTriggerTime = Timer.periodic(
    # you can specify any duration you want, roughly every 20 read from the system
          const Duration(seconds: 5),
          (timer) {
            Clipboard.getData('text/plain').then((clipboarContent) {
              print('Clipboard content ${clipboarContent.text}');
    
              # post to a Stream you're subscribed to
              clipboardContentStream.add(clipboarContent.text);
            });
          },
        );
    
    # subscribe your view with
    Stream get clipboardText => clipboardController.stream
    
    # and don't forget to clean up on your widget
    @override
    void dispose() {
      clipboardContentStream.close();
    
      clipboardTriggerTime.cancel();
    }
    
    0 讨论(0)
提交回复
热议问题