Add SelectionListener/SelectedContentRange (#154202)

https://github.com/user-attachments/assets/59225cf7-5506-414e-87da-aa4d3227e7f6

Adds:
* `SelectionListener`, allows a user to listen to selection changes
under the subtree it wraps given their is an ancestor `SelectionArea` or
`SelectableRegion`. These selection changes can be listened to through
the `SelectionListenerNotifier` that is provided to a
`SelectionListener`.
* `SelectionListenerNotifier`, used with `SelectionListener`, allows a
user listen to selection changes for the subtree of the
`SelectionListener` it was provided to. Provides access to individual
selection values through the `SelectionDetails` object `selection`.
* `SelectableRegionSelectionStatusScope`, allows the user to listen to
when a parent `SelectableRegion` is changing or finalizing the
selection.
* `SelectedContentRange`, provides information about the selection range
under a `SelectionHandler` or `Selectable` through the `getSelection()`
method. This includes a start and end offset relative to the
`Selectable`s content.
* `SelectionHandler.contentLength`, to describe the length of the
content contained by a selectable.

Original PR & Discussion: https://github.com/flutter/flutter/pull/148998

Fixes: #110594

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

---------

Co-authored-by: Renzo Olivares <roliv@google.com>
This commit is contained in:
Renzo Olivares
2024-11-25 16:14:30 -08:00
committed by GitHub
parent 4051a38dd7
commit f3f72ede04
14 changed files with 1664 additions and 34 deletions

View File

@@ -94,7 +94,7 @@ class _RenderSelectableAdapter extends RenderProxyBox with Selectable, Selection
final ValueNotifier<SelectionGeometry> _geometry;
Color get selectionColor => _selectionColor;
late Color _selectionColor;
Color _selectionColor;
set selectionColor(Color value) {
if (_selectionColor == value) {
return;
@@ -272,6 +272,20 @@ class _RenderSelectableAdapter extends RenderProxyBox with Selectable, Selection
return value.hasSelection ? const SelectedContent(plainText: 'Custom Text') : null;
}
@override
SelectedContentRange? getSelection() {
if (!value.hasSelection) {
return null;
}
return const SelectedContentRange(
startOffset: 0,
endOffset: 1,
);
}
@override
int get contentLength => 1;
LayerLink? _startHandle;
LayerLink? _endHandle;

View File

@@ -0,0 +1,136 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Flutter code sample for [SelectionArea].
void main() => runApp(const SelectionAreaSelectionListenerExampleApp());
class SelectionAreaSelectionListenerExampleApp extends StatelessWidget {
const SelectionAreaSelectionListenerExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final SelectionListenerNotifier _selectionNotifier = SelectionListenerNotifier();
SelectableRegionSelectionStatus? _selectableRegionStatus;
void _handleOnSelectionStateChanged(SelectableRegionSelectionStatus status) {
setState(() {
_selectableRegionStatus = status;
});
}
@override
void dispose() {
_selectionNotifier.dispose();
_selectableRegionStatus = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
for (final (int? offset, String label) in <(int? offset, String label)>[
(_selectionNotifier.registered ? _selectionNotifier.selection.range?.startOffset : null, 'StartOffset'),
(_selectionNotifier.registered ? _selectionNotifier.selection.range?.endOffset : null, 'EndOffset'),
])
Text('Selection $label: $offset'),
Text('Selection Status: ${_selectionNotifier.registered ? _selectionNotifier.selection.status : 'SelectionListenerNotifier not registered.'}'),
Text('Selectable Region Status: $_selectableRegionStatus'),
],
),
const SizedBox(height: 15.0,),
SelectionArea(
child: MySelectableText(
selectionNotifier: _selectionNotifier,
onChanged: _handleOnSelectionStateChanged,
),
),
],
),
),
);
}
}
class MySelectableText extends StatefulWidget {
const MySelectableText({
super.key,
required this.selectionNotifier,
required this.onChanged,
});
final SelectionListenerNotifier selectionNotifier;
final ValueChanged<SelectableRegionSelectionStatus> onChanged;
@override
State<MySelectableText> createState() => _MySelectableTextState();
}
class _MySelectableTextState extends State<MySelectableText> {
ValueListenable<SelectableRegionSelectionStatus>? _selectableRegionScope;
void _handleOnSelectableRegionChanged() {
if (_selectableRegionScope == null) {
return;
}
widget.onChanged.call(_selectableRegionScope!.value);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged);
_selectableRegionScope = SelectableRegionSelectionStatusScope.maybeOf(context);
_selectableRegionScope?.addListener(_handleOnSelectableRegionChanged);
}
@override
void dispose() {
_selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged);
_selectableRegionScope = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return SelectionListener(
selectionNotifier: widget.selectionNotifier,
child: const Text('This is some text under a SelectionArea that can be selected.'),
);
}
}

View File

@@ -0,0 +1,407 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Flutter code sample for [SelectionArea].
void main() => runApp(const SelectionAreaColorTextRedExampleApp());
class SelectionAreaColorTextRedExampleApp extends StatelessWidget {
const SelectionAreaColorTextRedExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
typedef LocalSpanRange = ({int startOffset, int endOffset});
class _MyHomePageState extends State<MyHomePage> {
final SelectionListenerNotifier _selectionNotifier = SelectionListenerNotifier();
final ContextMenuController _menuController = ContextMenuController();
final GlobalKey<SelectionAreaState> selectionAreaKey = GlobalKey<SelectionAreaState>();
// The data of the top level TextSpans. Each TextSpan is mapped to a LocalSpanRange,
// which is the range the textspan covers relative to the SelectionListener it is under.
Map<LocalSpanRange, TextSpan> dataSourceMap = <LocalSpanRange, TextSpan>{};
// The data of the bulleted list contained within a WidgetSpan. Each bullet is mapped
// to a LocalSpanRange, being the range the bullet covers relative to the SelectionListener
// it is under.
Map<LocalSpanRange, TextSpan> bulletSourceMap = <LocalSpanRange, TextSpan>{};
Map<int, Map<LocalSpanRange, TextSpan>> widgetSpanMaps = <int, Map<LocalSpanRange, TextSpan>>{};
// The origin data used to restore the demo to its initial state.
late final Map<LocalSpanRange, TextSpan> originSourceData;
late final Map<LocalSpanRange, TextSpan> originBulletSourceData;
void _initData() {
const String bulletListTitle = 'This is some bulleted list:\n';
final List<String> bullets = <String>[
for (int i = 1; i <= 7; i += 1)
'• Bullet $i'
];
final TextSpan bulletedList = TextSpan(
text: bulletListTitle,
children: <InlineSpan>[
WidgetSpan(
child: Column(
children: <Widget>[
for (final String bullet in bullets)
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(bullet),
)
],
),
),
],
);
int currentOffset = 0;
// Map bulleted list span to a local range using its concrete length calculated
// from the length of its title and each individual bullet.
dataSourceMap[(startOffset: currentOffset, endOffset: bulletListTitle.length + bullets.join().length)] = bulletedList;
currentOffset += bulletListTitle.length;
widgetSpanMaps[currentOffset] = bulletSourceMap;
// Map individual bullets to a local range.
for (final String bullet in bullets) {
bulletSourceMap[(startOffset: currentOffset, endOffset: currentOffset + bullet.length)] = TextSpan(text: bullet);
currentOffset += bullet.length;
}
const TextSpan secondTextParagraph = TextSpan(
text: 'This is some text in a text widget.',
children: <InlineSpan>[TextSpan(text: ' This is some more text in the same text widget.')],
);
const TextSpan thirdTextParagraph = TextSpan(text: 'This is some text in another text widget.');
// Map second and third paragraphs to local ranges.
dataSourceMap[(startOffset: currentOffset, endOffset: currentOffset + secondTextParagraph.toPlainText(includeSemanticsLabels: false).length)] = secondTextParagraph;
currentOffset += secondTextParagraph.toPlainText(includeSemanticsLabels: false).length;
dataSourceMap[(startOffset: currentOffset, endOffset: currentOffset + thirdTextParagraph.toPlainText(includeSemanticsLabels: false).length)] = thirdTextParagraph;
// Save the origin data so we can revert our changes.
originSourceData = <LocalSpanRange, TextSpan>{};
for (final MapEntry<LocalSpanRange, TextSpan> entry in dataSourceMap.entries) {
originSourceData[entry.key] = entry.value;
}
originBulletSourceData = <LocalSpanRange, TextSpan>{};
for (final MapEntry<LocalSpanRange, TextSpan> entry in bulletSourceMap.entries) {
originBulletSourceData[entry.key] = entry.value;
}
}
void _handleSelectableRegionStatusChanged(SelectableRegionSelectionStatus status) {
if (_menuController.isShown) {
ContextMenuController.removeAny();
}
if (_selectionNotifier.selection.status != SelectionStatus.uncollapsed
|| status != SelectableRegionSelectionStatus.finalized) {
return;
}
if (selectionAreaKey.currentState == null
|| !selectionAreaKey.currentState!.mounted
|| selectionAreaKey.currentState!.selectableRegion.contextMenuAnchors.secondaryAnchor == null) {
return;
}
final SelectedContentRange? selectedContentRange = _selectionNotifier.selection.range;
if (selectedContentRange == null) {
return;
}
_menuController.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return TapRegion(
onTapOutside: (PointerDownEvent event) {
if (_menuController.isShown) {
ContextMenuController.removeAny();
}
},
child: AdaptiveTextSelectionToolbar.buttonItems(
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
_colorSelectionRed(
selectedContentRange,
dataMap: dataSourceMap,
coloringChildSpan: false,
);
selectionAreaKey.currentState!.selectableRegion.clearSelection();
},
label: 'Color Text Red',
),
],
anchors: TextSelectionToolbarAnchors(primaryAnchor: selectionAreaKey.currentState!.selectableRegion.contextMenuAnchors.secondaryAnchor!),
),
);
},
);
}
void _colorSelectionRed(
SelectedContentRange selectedContentRange, {
required Map<LocalSpanRange, TextSpan> dataMap,
required bool coloringChildSpan,
}) {
for (final MapEntry<LocalSpanRange, TextSpan> entry in dataMap.entries) {
final LocalSpanRange entryLocalRange = entry.key;
final int normalizedStartOffset = min(selectedContentRange.startOffset, selectedContentRange.endOffset);
final int normalizedEndOffset = max(selectedContentRange.startOffset, selectedContentRange.endOffset);
if (normalizedStartOffset > entryLocalRange.endOffset) {
continue;
}
if (normalizedEndOffset < entryLocalRange.startOffset) {
continue;
}
// The selection details is covering the current entry so let's color the range red.
final TextSpan rawSpan = entry.value;
// Determine local ranges relative to rawSpan.
final int clampedLocalStart = normalizedStartOffset < entryLocalRange.startOffset ? entryLocalRange.startOffset : normalizedStartOffset;
final int clampedLocalEnd = normalizedEndOffset > entryLocalRange.endOffset ? entryLocalRange.endOffset : normalizedEndOffset;
final int startOffset = (clampedLocalStart - entryLocalRange.startOffset).abs();
final int endOffset = startOffset + (clampedLocalEnd - clampedLocalStart).abs();
final List<InlineSpan> beforeSelection = <InlineSpan>[];
final List<InlineSpan> insideSelection = <InlineSpan>[];
final List<InlineSpan> afterSelection = <InlineSpan>[];
int count = 0;
rawSpan.visitChildren((InlineSpan child) {
if (child is TextSpan) {
final String? rawText = child.text;
if (rawText != null) {
if (count < startOffset) {
final int newStart = min(startOffset - count, rawText.length);
final int globalNewStart = count + newStart;
// Collect spans before selection.
beforeSelection.add(
TextSpan(
style: child.style,
text: rawText.substring(0, newStart),
),
);
// Check if this span also contains the selection.
if (globalNewStart == startOffset && newStart < rawText.length) {
final int newStartAfterSelection = min(newStart + (endOffset - startOffset), rawText.length);
final int globalNewStartAfterSelection = count + newStartAfterSelection;
insideSelection.add(
TextSpan(
style: const TextStyle(color: Colors.red).merge(entry.value.style),
text: rawText.substring(newStart, newStartAfterSelection),
),
);
// Check if this span contains content after the selection.
if (globalNewStartAfterSelection == endOffset && newStartAfterSelection < rawText.length) {
afterSelection.add(
TextSpan(
style: child.style,
text: rawText.substring(newStartAfterSelection),
),
);
}
}
} else if (count >= endOffset) {
// Collect spans after selection.
afterSelection.add(TextSpan(style: child.style, text: rawText));
} else {
// Collect spans inside selection.
final int newStart = min(endOffset - count, rawText.length);
final int globalNewStart = count + newStart;
insideSelection.add(TextSpan(style: const TextStyle(color: Colors.red), text: rawText.substring(0, newStart)));
// Check if this span contains content after the selection.
if (globalNewStart == endOffset && newStart < rawText.length) {
afterSelection.add(TextSpan(style: child.style, text: rawText.substring(newStart)));
}
}
count += rawText.length;
}
} else if (child is WidgetSpan) {
if (!widgetSpanMaps.containsKey(count)) {
// We have arrived at a WidgetSpan but it is unaccounted for.
return true;
}
final Map<LocalSpanRange, TextSpan> widgetSpanSourceMap = widgetSpanMaps[count]!;
if (count < startOffset && count + (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs() < startOffset) {
// When the count is less than the startOffset and we are at a widgetspan
// it is still possible that the startOffset is somewhere within the widgetspan,
// so we should try to color the selection red for the widgetspan.
//
// If the calculated widgetspan length would not extend the count past the
// startOffset then add this widgetspan to the beforeSelection, and
// continue walking the tree.
beforeSelection.add(child);
count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs();
return true;
} else if (count >= endOffset) {
afterSelection.add(child);
count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs();
return true;
}
// Update widgetspan data.
_colorSelectionRed(
selectedContentRange,
dataMap: widgetSpanSourceMap,
coloringChildSpan: true,
);
// Re-create widgetspan.
if (count == 28) { // The index where the bulleted list begins.
insideSelection.add(
WidgetSpan(
child: Column(
children: <Widget>[
for (final MapEntry<LocalSpanRange, TextSpan> entry in widgetSpanSourceMap.entries)
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text.rich(
widgetSpanSourceMap[entry.key]!,
),
)
],
),
),
);
}
count += (widgetSpanSourceMap.keys.last.endOffset - widgetSpanSourceMap.keys.first.startOffset).abs();
return true;
}
return true;
});
dataMap[entry.key] = TextSpan(
style: dataMap[entry.key]!.style,
children: <InlineSpan>[
...beforeSelection,
...insideSelection,
...afterSelection,
],
);
}
// Avoid clearing the selection and setting the state
// before we have colored all parts of the selection.
if (!coloringChildSpan) {
setState(() {});
}
}
@override
void initState() {
super.initState();
_initData();
}
@override
void dispose() {
_selectionNotifier.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: SelectionArea(
key: selectionAreaKey,
child: MySelectableTextColumn(
selectionNotifier: _selectionNotifier,
dataSourceMap: dataSourceMap,
onChanged: _handleSelectableRegionStatusChanged,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
// Resets the state to the origin data.
for (final MapEntry<LocalSpanRange, TextSpan> entry in originSourceData.entries) {
dataSourceMap[entry.key] = entry.value;
}
for (final MapEntry<LocalSpanRange, TextSpan> entry in originBulletSourceData.entries) {
bulletSourceMap[entry.key] = entry.value;
}
});
},
child: const Icon(Icons.undo),
),
);
}
}
class MySelectableTextColumn extends StatefulWidget {
const MySelectableTextColumn({
super.key,
required this.selectionNotifier,
required this.dataSourceMap,
required this.onChanged,
});
final SelectionListenerNotifier selectionNotifier;
final Map<LocalSpanRange, TextSpan> dataSourceMap;
final ValueChanged<SelectableRegionSelectionStatus> onChanged;
@override
State<MySelectableTextColumn> createState() => _MySelectableTextColumnState();
}
class _MySelectableTextColumnState extends State<MySelectableTextColumn> {
ValueListenable<SelectableRegionSelectionStatus>? _selectableRegionScope;
void _handleOnSelectableRegionChanged() {
if (_selectableRegionScope == null) {
return;
}
widget.onChanged.call(_selectableRegionScope!.value);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged);
_selectableRegionScope = SelectableRegionSelectionStatusScope.maybeOf(context);
_selectableRegionScope?.addListener(_handleOnSelectableRegionChanged);
}
@override
void dispose() {
_selectableRegionScope?.removeListener(_handleOnSelectableRegionChanged);
_selectableRegionScope = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return SelectionListener(
selectionNotifier: widget.selectionNotifier,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (final MapEntry<LocalSpanRange, TextSpan> entry in widget.dataSourceMap.entries)
Text.rich(
entry.value,
),
],
),
),
);
}
}

View File

@@ -0,0 +1,21 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/selection_area/selection_area.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SelectionArea SelectionListener Example Smoke Test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SelectionAreaSelectionListenerExampleApp(),
);
expect(find.byType(Column), findsNWidgets(2));
expect(find.textContaining('Selection StartOffset:'), findsOneWidget);
expect(find.textContaining('Selection EndOffset:'), findsOneWidget);
expect(find.textContaining('Selection Status:'), findsOneWidget);
expect(find.textContaining('Selectable Region Status:'), findsOneWidget);
expect(find.textContaining('This is some text under a SelectionArea that can be selected.'), findsOneWidget);
});
}

View File

@@ -0,0 +1,125 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_api_samples/material/selection_area/selection_area.2.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SelectionArea Color Text Red Example Smoke Test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SelectionAreaColorTextRedExampleApp(),
);
expect(find.widgetWithIcon(FloatingActionButton, Icons.undo), findsOneWidget);
expect(find.byType(Column), findsNWidgets(2));
expect(find.textContaining('This is some bulleted list:\n'), findsOneWidget);
for (int i = 1; i <= 7; i += 1) {
expect(find.widgetWithText(Text, '• Bullet $i'), findsOneWidget);
}
expect(find.textContaining('This is some text in a text widget.'), findsOneWidget);
expect(find.textContaining(' This is some more text in the same text widget.'), findsOneWidget);
expect(find.textContaining('This is some text in another text widget.'), findsOneWidget);
});
testWidgets('SelectionArea Color Text Red Example - colors selected range red', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SelectionAreaColorTextRedExampleApp(),
);
await tester.pumpAndSettle();
final Finder paragraph1Finder = find.descendant(of: find.textContaining('This is some bulleted list').first, matching: find.byType(RichText).first);
final Finder paragraph3Finder = find.descendant(of: find.textContaining('This is some text in another text widget.'), matching: find.byType(RichText));
final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(paragraph1Finder);
final List<RenderParagraph> bullets = tester.renderObjectList<RenderParagraph>(find.descendant(of: find.textContaining('• Bullet'), matching: find.byType(RichText))).toList();
expect(bullets.length, 7);
final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.textContaining('This is some text in a text widget.'), matching: find.byType(RichText)));
final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(paragraph3Finder);
// Drag to select from paragraph 1 position 4 to paragraph 3 position 25.
final TestGesture gesture = await tester.startGesture(tester.getRect(paragraph1Finder).topLeft + const Offset(50.0, 10.0), kind: PointerDeviceKind.mouse);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(tester.getRect(paragraph3Finder).centerLeft + const Offset(360.0, 0.0));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
// Verify selection.
// Bulleted list title.
expect(paragraph1.selections.length, 1);
expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 27));
// Bulleted list.
for (final RenderParagraph paragraphBullet in bullets) {
expect(paragraphBullet.selections.length, 1);
expect(paragraphBullet.selections[0], const TextSelection(baseOffset: 0, extentOffset: 10));
}
// Second text widget.
expect(paragraph2.selections.length, 1);
expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 83));
// Third text widget.
expect(paragraph3.selections.length, 1);
expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 25));
// Color selection red.
expect(find.textContaining('Color Text Red'), findsOneWidget);
await tester.tap(find.textContaining('Color Text Red'));
await tester.pumpAndSettle();
// Verify selection is red.
final TextSpan paragraph1ResultingSpan = paragraph1.text as TextSpan;
final TextSpan paragraph2ResultingSpan = paragraph2.text as TextSpan;
final TextSpan paragraph3ResultingSpan = paragraph3.text as TextSpan;
// Title of bulleted list is partially red.
expect(paragraph1ResultingSpan.children, isNotNull);
expect(paragraph1ResultingSpan.children!.length, 1);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children, isNotNull);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children!.length, 3);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![0].style, isNull);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1], isA<TextSpan>());
expect(((paragraph1ResultingSpan.children![0] as TextSpan).children![1] as TextSpan).text, isNotNull);
expect(((paragraph1ResultingSpan.children![0] as TextSpan).children![1] as TextSpan).text, ' is some bulleted list:\n');
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style, isNotNull);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style!.color, isNotNull);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![1].style!.color, Colors.red);
expect((paragraph1ResultingSpan.children![0] as TextSpan).children![2], isA<WidgetSpan>());
// Bullets are red.
for (final RenderParagraph paragraphBullet in bullets) {
final TextSpan resultingBulletSpan = paragraphBullet.text as TextSpan;
expect(resultingBulletSpan.children, isNotNull);
expect(resultingBulletSpan.children!.length, 1);
expect(resultingBulletSpan.children![0], isA<TextSpan>());
expect((resultingBulletSpan.children![0] as TextSpan).children, isNotNull);
expect((resultingBulletSpan.children![0] as TextSpan).children!.length, 1);
expect((resultingBulletSpan.children![0] as TextSpan).children![0], isA<TextSpan>());
expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style, isNotNull);
expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style!.color, isNotNull);
expect(((resultingBulletSpan.children![0] as TextSpan).children![0] as TextSpan).style!.color, Colors.red);
}
// Second text widget is red.
expect(paragraph2ResultingSpan.children, isNotNull);
expect(paragraph2ResultingSpan.children!.length, 1);
expect(paragraph2ResultingSpan.children![0], isA<TextSpan>());
expect((paragraph2ResultingSpan.children![0] as TextSpan).children, isNotNull);
for (final InlineSpan span in (paragraph2ResultingSpan.children![0] as TextSpan).children!) {
if (span is TextSpan) {
expect(span.style, isNotNull);
expect(span.style!.color, isNotNull);
expect(span.style!.color, Colors.red);
}
}
// Part of third text widget is red.
expect(paragraph3ResultingSpan.children, isNotNull);
expect(paragraph3ResultingSpan.children!.length, 1);
expect(paragraph3ResultingSpan.children![0], isA<TextSpan>());
expect((paragraph3ResultingSpan.children![0] as TextSpan).children, isNotNull);
expect((paragraph3ResultingSpan.children![0] as TextSpan).children!.length, 2);
expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0], isA<TextSpan>());
expect(((paragraph3ResultingSpan.children![0] as TextSpan).children![0] as TextSpan).text, isNotNull);
expect(((paragraph3ResultingSpan.children![0] as TextSpan).children![0] as TextSpan).text, 'This is some text in ano');
expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style, isNotNull);
expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style!.color, isNotNull);
expect((paragraph3ResultingSpan.children![0] as TextSpan).children![0].style!.color, Colors.red);
expect((paragraph3ResultingSpan.children![0] as TextSpan).children![1].style, isNull);
});
}