Flutter文本高亮选择插件selectable_text_highlighter的使用
Flutter文本高亮选择插件selectable_text_highlighter的使用
该插件帮助您选择和高亮文本。您甚至可以为高亮和未高亮的文本设置不同的样式。此外,您还可以提供其他工具栏选项,如全选、剪切和复制。您还可以以高亮偏移量的形式提供预高亮的文本。
示例演示:
完整示例代码:
import 'package:flutter/material.dart';
import 'package:selectable_text_highlighter/selectable_text_highlighter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 应用程序的根部件。
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Screen1(),
);
}
}
class Screen1 extends StatefulWidget {
[@override](/user/override)
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
List<HighlightedOffset> offsets = [];
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('高亮选择演示'),),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
child: offsets.isEmpty ?
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.note, size: 60,),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('无文本高亮', style: TextStyle(fontSize: 18)),
),
],
),
)
: ListView.separated(
itemBuilder: (context, position){
return Dismissible(
key: Key(offsets[position].start.toString()),
onDismissed: (direction){
setState(() {
offsets.removeAt(position);
});
},
background: Container(
color: Colors.red,
),
child: Text(offsets[position].highlightedText));
},
separatorBuilder: (context, position){
return Divider(color: Colors.black87,);
}, itemCount: offsets.length)
),
],
),
),
floatingActionButton: FloatingActionButton(child: Center(child: Icon(Icons.arrow_forward_ios),),onPressed: ()async{
offsets = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyHomePage(offsets: offsets)));
setState(() {
});
},),
);
}
}
class MyHomePage extends StatefulWidget {
final List<HighlightedOffset>? offsets;
MyHomePage({Key? key, this.offsets}) : super(key: key);
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String paragraph = '''
Miusov, as a man man of breeding and deilcacy, could not but feel some inwrd qualms, when he reached the Father Superior's with Ivan: he felt ashamed of havin lost his temper. He felt that he ought to have disdaimed that despicable wretch, Fyodor Pavlovitch, too much to have been upset by him in Father Zossima's cell, and so to have forgotten himself. "Teh monks were not to blame, in any case," he reflceted, on the steps. "And if they're decent people here (and the Father Superior, I understand, is a nobleman) why not be friendly and courteous withthem? I won't argue, I'll fall in with everything, I'll win them by politness, and show them that I've nothing to do with that Aesop, thta buffoon, that Pierrot, and have merely been takken in over this affair, just as they have."
He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once. He was the more ready to do this becuase the rights had becom much less valuable, and he had indeed the vaguest idea where the wood and river in quedtion were.
These excellant intentions were strengthed when he enterd the Father Superior's diniing-room, though, stricttly speakin, it was not a dining-room, for the Father Superior had only two rooms alltogether; they were, however, much larger and more comfortable than Father Zossima's. But tehre was was no great luxury about the furnishng of these rooms eithar. The furniture was of mohogany, covered with leather, in the old-fashionned style of 1820 the floor was not even stained, but evreything was shining with cleanlyness, and there were many chioce flowers in the windows; the most sumptuous thing in the room at the moment was, of course, the beatifuly decorated table. The cloth was clean, the service shone; there were three kinds of well-baked bread, two bottles of wine, two of excellent mead, and a large glass jug of kvas -- both the latter made in the monastery, and famous in the neigborhood. There was no vodka. Rakitin related afterwards that there were five dishes: fish-suop made of sterlets, served with little fish paties; then boiled fish served in a spesial way; then salmon cutlets, ice pudding and compote, and finally, blanc-mange.
''';
int tempBaseOffset = 0;
int tempExtentOffset = 0;
List<HighlightedOffset> offsets = [];
[@override](/user/override)
void initState() {
offsets = widget.offsets ?? [];
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(onPressed: (){
Navigator.of(context).pop(offsets);
}, icon: Icon(Icons.arrow_back_ios)),
title: Text('第1章'),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: SelectableHighlighterText(
text: paragraph,
preHighlightedTexts: widget.offsets ?? [],
onHighlightedCallback: (list){
setState(() {
offsets = list;
});
},
)
),
],
),
),
// 这个逗号使自动格式化更美观。
);
}
}
更多关于Flutter文本高亮选择插件selectable_text_highlighter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter文本高亮选择插件selectable_text_highlighter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
selectable_text_highlighter
是一个 Flutter 插件,它允许你在文本中选择并高亮显示特定的部分。这个插件非常适合用于需要用户选择文本并对其进行高亮显示的场景,比如笔记应用、阅读应用等。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 selectable_text_highlighter
插件的依赖:
dependencies:
flutter:
sdk: flutter
selectable_text_highlighter: ^0.1.0 # 请检查最新版本
然后运行 flutter pub get
来安装插件。
基本用法
以下是一个简单的示例,展示了如何使用 selectable_text_highlighter
插件来选择和文本高亮:
import 'package:flutter/material.dart';
import 'package:selectable_text_highlighter/selectable_text_highlighter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Selectable Text Highlighter Example'),
),
body: Center(
child: SelectableTextHighlighter(
text: 'This is a sample text that you can select and highlight.',
onSelectionChanged: (selectedText, selectedRange) {
print('Selected Text: $selectedText');
print('Selected Range: $selectedRange');
},
highlightColor: Colors.yellow,
),
),
),
);
}
}
参数说明
text
: 要显示的文本内容。onSelectionChanged
: 当用户选择文本时触发的回调函数。它返回选中的文本和选中的范围。highlightColor
: 高亮显示的颜色。
高级用法
你还可以通过 SelectableTextHighlighter
的其他参数来自定义行为,例如:
style
: 文本的样式。textAlign
: 文本的对齐方式。textDirection
: 文本的方向。maxLines
: 文本的最大行数。overflow
: 文本溢出的处理方式。
示例代码
SelectableTextHighlighter(
text: 'This is a sample text that you can select and highlight.',
onSelectionChanged: (selectedText, selectedRange) {
print('Selected Text: $selectedText');
print('Selected Range: $selectedRange');
},
highlightColor: Colors.yellow,
style: TextStyle(fontSize: 18, color: Colors.black),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
);