文本选择弹出菜单

Text Selection Pop Menu

提问人:Shailaja Tripathi 提问时间:9/20/2023 更新时间:9/20/2023 访问量:52

问:

如果用户选择文本,则应有“快速笔记”菜单 会弹出,所以当用户在我的 flutter 项目中选择文本时,我需要显示一个弹出菜单。

当用户在我的 flutter 项目中选择文本时,我需要显示一个弹出菜单,任何人都可以给我任何例子吗

Android Flutter 弹出 PopupMenu TextSelection

评论

0赞 Community 9/21/2023
请澄清您的具体问题或提供其他详细信息以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。

答:

0赞 Godson 9/20/2023 #1
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Text Selection Menu Example'),
        ),
        body: TextSelectionMenuDemo(),
      ),
    );
  }
}

class TextSelectionMenuDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: SelectableText(
        'Select this text to show the popup menu.',
        style: TextStyle(fontSize: 18.0),
        onTap: () {
          // Handle text selection here (if needed).
        },
        onSelectionChanged: (TextSelection selection, SelectionChangedCause cause) {
          if (selection.baseOffset != selection.extentOffset) {
            // Text is selected, show the popup menu.
            showTextPopupMenu(context);
          }
        },
      ),
    );
  }

  void showTextPopupMenu(BuildContext context) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;

    final RenderBox text = context.findRenderObject() as RenderBox;
    final Offset offset = text.localToGlobal(Offset.zero, ancestor: overlay);

    final TextSelection selection = TextSelection(baseOffset: 0, extentOffset: 0);
    final List<PopupMenuEntry<String>> popupItems = [
      PopupMenuItem<String>(
        value: 'Copy',
        child: Text('Copy'),
      ),
      PopupMenuItem<String>(
        value: 'Cut',
        child: Text('Cut'),
      ),
      PopupMenuItem<String>(
        value: 'Paste',
        child: Text('Paste'),
      ),
    ];

    showMenu<String>(
      context: context,
      position: RelativeRect.fromRect(offset & text.size, Offset.zero & overlay.size),
      items: popupItems,
    ).then((String? selectedValue) {
      if (selectedValue != null) {
        // Handle selected menu item here.
        print('Selected: $selectedValue');
      }
    });
  }
}