12.7 C
New York
Tuesday, December 6, 2022

How to create selectable text in Flutter

This article shows you how to create selectable and copiable text in Flutter.

Overview

In Flutter, the text presented by the Text widget is undetectable (even on the web). To make text selectable, you can use the SelectableText widget. Advertisements

If you want to create single style selectable text, use this constructor:

SelectableText(
   String data, 
   {
      Key? key, 
      FocusNode? focusNode, 
      TextStyle? style, 
      StrutStyle? strutStyle, 
      TextAlign? textAlign, 
      TextDirection? textDirection, 
      double? textScaleFactor, 
      bool showCursor = false, 
      bool autofocus = false, 
      ToolbarOptions? toolbarOptions, 
      int? minLines, 
      int? maxLines, 
      double cursorWidth = 2.0, 
      double? cursorHeight, 
      Radius? cursorRadius, 
      Color? cursorColor, 
      selectionHeightStyle = ui.BoxHeightStyle.tight, 
      BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
      DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
      bool enableInteractiveSelection = true, 
      TextSelectionControls? selectionControls, 
      GestureTapCallback? onTap, 
      ScrollPhysics? scrollPhysics, 
      String? semanticsLabel, 
      TextHeightBehavior? textHeightBehavior, 
      TextWidthBasis? textWidthBasis, 
      SelectionChangedCallback? onSelectionChanged
    }
)

If you want to implement multi-style selectable text, use this constructor:

SelectableText.rich(
   TextSpan textSpan, 
   {
     Key? key, 
     FocusNode? focusNode, 
     TextStyle? style, 
     StrutStyle? strutStyle, 
     TextAlign? textAlign, 
     TextDirection? textDirection, 
     double? textScaleFactor, 
     bool showCursor = false, 
     bool autofocus = false, 
     ToolbarOptions? toolbarOptions, 
     int? minLines, int? maxLines, 
     double cursorWidth = 2.0, 
     double? cursorHeight, 
     Radius? cursorRadius, 
     Color? cursorColor, 
     BoxHeightStyle selectionHeightStyle = ui.BoxHeightStyle.tight, 
     BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
     DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
     bool enableInteractiveSelection = true, 
     TextSelectionControls? selectionControls, 
     GestureTapCallback? onTap, 
     ScrollPhysics? scrollPhysics, 
     String? semanticsLabel, 
     TextHeightBehavior? textHeightBehavior, 
     TextWidthBasis? textWidthBasis, 
     SelectionChangedCallback? onSelectionChanged
   }
)

You can find more detailed information in the official docs.

Complete Example

App Preview

AdvertisementsIn this example, we’ll implement selectable text by using both SelectableText and SelectableText.rich constructors. The user can select and copy text and paste them to the multi-line text field:

Note: If you’re using Safari, this demo video might not work nicely or not start at all. Please use Chrome, Edge, Firefox, or another web browser instead.

The Code

The full source code with explanations:

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('KindaCode.com')),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [
            // SelectableText
            SelectableText(
              'Please copy me',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 30,
            ),
            TextField(
              minLines: 3,
              maxLines: 10,
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Paste your text here'),
            ),
            SizedBox(
              height: 30,
            ),
            // SelectableText.rich
            SelectableText.rich(TextSpan(
                text: 'He thrusts his fists ',
                style: TextStyle(fontSize: 20),
                children: [
                  TextSpan(
                      text: 'against the posts',
                      style: TextStyle(color: Colors.blue)),
                  TextSpan(
                      text: 'and still insists he sees the ghosts.',
                      style: TextStyle(color: Colors.red))
                ])),
          ],
        ),
      ),
    );
  }
}

Conclusion

Advertisements

You’ve learned how to create selectable and copiable text with the SelectableText widget. If you’d like to explore more new and fascinating things in the modern Flutter world, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles