How to change selected text color locally - flutter

Viewed 4817

Text selection color can be changed by globally setting the theme:

    theme: ThemeData.light().copyWith(
        accentColor: kPrimaryAccent,
        primaryColor: kPrimaryColor,
        textSelectionColor: kTextSelectionColor,
        textSelectionHandleColor: kPrimaryAccent)

But how can this be done locally in a single text-field?

2 Answers

Since the property mentioned in Mobina answer become deprecated, here is how you do it in early 2022:

Container(
  child: Theme(
    data: ThemeData(
      textSelectionTheme: const TextSelectionThemeData(
        cursorColor: Colors.yellow,
        selectionColor: Colors.green,
        selectionHandleColor: Colors.blue,
      )
    ),
    child: SelectableText(
      'this is a text',
    ),
  ),
),

Source: TextSelectionTheme migration

You can wrap your widget with a Theme and set the textSelectionColor for its ThemeData:

Container(
  child: Theme(
    data: ThemeData(
      textSelectionColor: Colors.yellow,
    ),
    child: SelectableText(
      'this is a text',
    ),
  ),
),
Related