You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SelectionArea中程序化设置选中文本?

如何编程设置Flutter SelectionArea的选中内容

要通过代码控制SelectionArea的选中内容,核心是用SelectionController关联SelectionArea并操作选中范围,具体步骤如下:

  • 第一步:创建SelectionController实例,将其绑定到SelectionArea的controller参数上,以此建立控制器与选中区域的关联。
  • 第二步:调用控制器的updateSelection方法,传入选中范围的起始偏移量(baseOffset)和结束偏移量(extentOffset),即可指定选中内容。

代码示例

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('SelectionArea 编程选中示例')),
        body: const SelectionDemo(),
      ),
    );
  }
}

class SelectionDemo extends StatefulWidget {
  const SelectionDemo({super.key});

  @override
  State<SelectionDemo> createState() => _SelectionDemoState();
}

class _SelectionDemoState extends State<SelectionDemo> {
  late final SelectionController _selectionController;

  @override
  void initState() {
    super.initState();
    _selectionController = SelectionController();
  }

  @override
  void dispose() {
    _selectionController.dispose();
    super.dispose();
  }

  // 编程设置选中范围:选中第3到第12个字符(偏移量从0开始计数)
  void _setSelection() {
    _selectionController.updateSelection(
      const TextSelection(baseOffset: 2, extentOffset: 11),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          SelectionArea(
            controller: _selectionController,
            child: const Text('这是一段用于测试选中的示例文本,看看编程选中是否生效'),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _setSelection,
            child: const Text('设置选中内容'),
          ),
        ],
      ),
    );
  }
}

注意事项

  • baseOffset和extentOffset是文本的字符偏移量,从0开始计数。如果baseOffset大于extentOffset,会形成反向选中(从右往左选)。
  • 偏移量必须在文本的有效长度范围内,否则选中设置不会生效。
  • 使用完SelectionController后,要在dispose方法中释放资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Microbob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 12:14:52