如果你想有一個通用的解決方案來放置小部件對文本,see this gist的部分。
您可以使用下面的代碼有限制的文本的特定部分的紋波:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' show TextBox;
import 'dart:math';
void main() {
runApp(new MaterialApp(
home: new Material(
child: new Center(
child: new Demo(),
),
),
));
}
class Demo extends StatelessWidget {
final TextSelection textSelection =
const TextSelection(baseOffset: 17, extentOffset: 21);
final GlobalKey _textKey = new GlobalKey();
@override
Widget build(context) => new Stack(
children: <Widget>[
new RichText(
key: _textKey,
text: new TextSpan(
text: 'HELLO THIS IS MY ',
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
new TextSpan(
text: 'LONG',
style: new TextStyle(fontWeight: FontWeight.bold)),
new TextSpan(text: ' SENTENCE'),
],
),
),
new Positioned.fill(
child: new LayoutBuilder(
builder: (context, _) => new Stack(
children: <Widget>[
new Positioned.fromRect(
rect: _getSelectionRect(),
child: new InkWell(
onTap:() => {}, // needed to show the ripple
),
),
],
),
),
),
],
);
Rect _getSelectionRect() =>
(_textKey.currentContext.findRenderObject() as RenderParagraph)
.getBoxesForSelection(textSelection)
.fold(
null,
(Rect previous, TextBox textBox) => new Rect.fromLTRB(
min(previous?.left ?? textBox.left, textBox.left),
min(previous?.top ?? textBox.top, textBox.top),
max(previous?.right ?? textBox.right, textBox.right),
max(previous?.bottom ?? textBox.bottom, textBox.bottom),
),
) ??
Rect.zero;
}
所以,關鍵是TextSelection偏移量需要匹配要皺子的帽子? –
@SethLadd是的,它甚至不必遵循文本跨度 – Takhion