我有一個這樣的文本跨度串列
var spans = [
TextSpan(text: content, style: style),
TextSpan(text: content, style: style)
//and 100 more
]
我像這樣在 SingleChildScrollView 中加載它。
SingleChildScrollView(
controller: scrollController,
child: Text.rich(
TextSpan(children: spans),
),
)
現在我的問題是如何在TextSpan串列之間轉移焦點?假設我想從螢屏頂部的串列中加載TextSpan位置 10而無需手動滾動。spans
uj5u.com熱心網友回復:
您可以在WidgetSpan每個 旁邊添加一個TextSpan,因此您可以為其分配一個key屬性,該屬性將是 aGlobalKey以便您可以訪問它BuildContext來呼叫該方法Scrollable.ensureVisible()。
這是一個受類似問題答案啟發的代碼示例:
class ScrollToTextSpanPage extends StatefulWidget {
const ScrollToTextSpanPage({Key? key}) : super(key: key);
@override
State<ScrollToTextSpanPage> createState() => _ScrollToTextSpanPageState();
}
class _ScrollToTextSpanPageState extends State<ScrollToTextSpanPage> {
final _keys = List<GlobalKey>.generate(
_kTextBlocks.length,
(_) => GlobalKey(),
);
void _goToSpan(int spanIndex) {
Scrollable.ensureVisible(
_keys[spanIndex].currentContext!,
alignment: 0.2,
duration: const Duration(milliseconds: 300),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Scroll to TextSpan'),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _goToSpan(8),
label: const Text('Go to span 8'),
icon: const Icon(Icons.navigate_next),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Text.rich(
TextSpan(
children: [
for (int i = 0; i < _kTextBlocks.length; i ) ...[
WidgetSpan(child: SizedBox(key: _keys[i])),
TextSpan(
text: 'Span $i\n',
style: const TextStyle(fontWeight: FontWeight.bold),
children: [
TextSpan(
text: '${_kTextBlocks[i]}\n\n',
style: const TextStyle(fontWeight: FontWeight.normal),
),
],
),
],
],
),
),
),
);
}
}
在 DartPad 上試用示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478461.html
上一篇:飛鏢中的異步.sort()
下一篇:如何從API獲取json
