flutter_profanity_filter
是一个用于检测和过滤不雅词汇的 Flutter 插件。它可以帮助你在应用中识别和替换不雅词汇,从而保持内容的清洁和友好。以下是如何使用 flutter_profanity_filter
的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 flutter_profanity_filter
依赖:
dependencies:
flutter:
sdk: flutter
flutter_profanity_filter: ^最新版本
然后运行 flutter pub get
来获取依赖。
2. 导入包
在你的 Dart 文件中导入 flutter_profanity_filter
包:
import 'package:flutter_profanity_filter/flutter_profanity_filter.dart';
3. 使用插件
你可以使用 FlutterProfanityFilter
类来检测和过滤不雅词汇。
检测不雅词汇
要检测文本中是否包含不雅词汇,可以使用 hasProfanity
方法:
final filter = FlutterProfanityFilter();
void checkTextForProfanity() {
String text = "This is a bad word example.";
bool hasProfanity = filter.hasProfanity(text);
print('Contains profanity: $hasProfanity');
}
过滤不雅词汇
如果你想过滤掉文本中的不雅词汇,可以使用 filter
方法。默认情况下,不雅词汇会被替换为星号 (*
),但你也可以自定义替换字符:
void filterText() {
String text = "This is a bad word example.";
String filteredText = filter.filter(text);
print('Filtered text: $filteredText');
// 自定义替换字符
String customFilteredText = filter.filter(text, replaceWith: '#');
print('Custom filtered text: $customFilteredText');
}
4. 添加自定义词汇
你还可以添加自定义的不雅词汇到过滤器中:
void addCustomWords() {
filter.addWords(['customWord1', 'customWord2']);
}
5. 示例代码
以下是一个完整的示例代码,展示了如何使用 flutter_profanity_filter
来检测和过滤不雅词汇:
import 'package:flutter/material.dart';
import 'package:flutter_profanity_filter/flutter_profanity_filter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: ProfanityFilterExample(),
);
}
}
class ProfanityFilterExample extends StatelessWidget {
final filter = FlutterProfanityFilter();
void checkTextForProfanity() {
String text = "This is a bad word example.";
bool hasProfanity = filter.hasProfanity(text);
print('Contains profanity: $hasProfanity');
}
void filterText() {
String text = "This is a bad word example.";
String filteredText = filter.filter(text);
print('Filtered text: $filteredText');
// 自定义替换字符
String customFilteredText = filter.filter(text, replaceWith: '#');
print('Custom filtered text: $customFilteredText');
}
void addCustomWords() {
filter.addWords(['customWord1', 'customWord2']);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Profanity Filter Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: checkTextForProfanity,
child: Text('Check Text for Profanity'),
),
ElevatedButton(
onPressed: filterText,
child: Text('Filter Text'),
),
ElevatedButton(
onPressed: addCustomWords,
child: Text('Add Custom Words'),
),
],
),
),
);
}
}