Ad

Flutter, How To Paste Data On Text Widget After Pressing The Button?

- 1 answer

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.

Ad

Answer

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;
    });
  }
}
Ad
source: stackoverflow.com
Ad