在SelectionArea中设置选定的文本

问题描述 投票:0回答:1

我了解如何阅读

SelectionArea
中选定的文本,但我也想做出选择。如果可以访问
SelectionArea
,我如何以编程方式设置它正在选择的内容?

谢谢!

flutter dart text textselection
1个回答
0
投票

据我所知,SelectionArea 没有一个简单的方法来做到这一点,或者至少我还没有看到有关它的文档,我在其中看到了可以在 TextFields 中完成的操作,在这里我给您留下一个示例。

import 'package:flutter/material.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final TextEditingController controller = TextEditingController()
    ..text = 'Hello World example';
  final FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material App Bar'),
        ),
        body: Center(
          child: Column(
            children: [
              TextField(
                focusNode: focusNode,
                controller: controller,
              ),
              TextButton(
                  onPressed: () {
                    //focus
                    focusNode.requestFocus();

                    //select all
                    controller.selection = TextSelection(
                        baseOffset: 0,
                        extentOffset: controller.text.length,
                        isDirectional: true);
                  },
                  child: const Text('Select All'))
            ],
          ),
        ),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.