Home > Mobile >  Flutter, how to paste data on Text Widget after pressing the button?
Flutter, how to paste data on Text Widget after pressing the button?

Time:10-15

For beginning i am really sorry for my not perfect English ;)

I copy data from an application and i want tap button in my application , it get data copied and paste on Widget Text

Thank you in advance for your help.

CodePudding user response:

There is a service for that called Clipboard which will allow you to access the system's clipboard/pasteboard. It will give you some ClipboardData which will contain some text.

  void _getClipboardText() async {
    final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
    String? clipboardText = clipboardData?.text;
    print(clipboardText);
  }

Full example of how to set it to a Text widget

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? _clipboardText;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (_clipboardText?.isNotEmpty == true)
              Text(
                '$_clipboardText',
                style: Theme.of(context).textTheme.headline4,
              ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getClipboardText,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  void _getClipboardText() async {
    final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
    setState(() {
      _clipboardText = clipboardData?.text;
    });
  }
}
  • Related