如何在Dart代码中隐藏阿拉伯语脏话检测方法或列表?
解决阿拉伯语脏话检测列表隐藏问题的几种方案
1. 将脏话列表移至外部资源文件
把脏话列表单独存放在JSON资源文件中,代码运行时动态读取,避免源码直接暴露脏话内容:
- 第一步:在项目
assets目录下创建arabic_profanity.json文件,内容为脏话数组:
["كسمك", "بنت الشرموطة", "الزاني", ...]
- 第二步:在
pubspec.yaml中声明资源:
flutter: assets: - assets/arabic_profanity.json
- 第三步:修改检测方法,从资源文件读取列表(可提前缓存列表避免重复IO):
import 'dart:convert'; import 'package:flutter/services.dart'; // 缓存加载后的脏话列表 List<String>? _cachedProfaneWords; bool hasArabicProfanity(String input) { // 首次调用时加载资源 _cachedProfaneWords ??= _loadProfaneWordsSync(); for (String word in _cachedProfaneWords!) { if (input.contains(word)) { return true; } } return false; } // 同步加载资源的辅助方法 List<String> _loadProfaneWordsSync() { String jsonString = rootBundle.loadStringSync('assets/arabic_profanity.json'); return List<String>.from(json.decode(jsonString)); }
2. 预生成哈希列表(解决手动哈希耗时问题)
不用手动逐个处理,写个简单脚本离线生成脏话的哈希值列表,代码里只存哈希值,检测时对输入内容计算哈希对比:
- 第一步:写个Dart脚本生成哈希列表(比如
generate_hashes.dart):
import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; void main() { List<String> profaneWords = ["كسمك", "بنت الشرموطة", ...]; // 原脏话列表 List<String> hashes = profaneWords.map((word) { return sha256.convert(utf8.encode(word)).toString(); }).toList(); // 将哈希列表写入文件,直接复制到代码中即可 File('profane_hashes.txt').writeAsStringSync(json.encode(hashes)); }
- 第二步:将生成的哈希数组复制到检测方法中:
import 'dart:convert'; import 'package:crypto/crypto.dart'; bool hasArabicProfanity(String input) { final List<String> profaneHashes = [ "abc123...", // 对应脏话的SHA-256哈希 "def456...", ... ]; // 拆分输入为单词(或按需求处理子串)计算哈希对比 List<String> inputWords = input.split(RegExp(r'\s+')); for (String word in inputWords) { String hash = sha256.convert(utf8.encode(word)).toString(); if (profaneHashes.contains(hash)) { return true; } } return false; }
注:哈希存在极小冲突概率,可额外存储单词长度做双重校验,进一步降低风险。
3. 封装为私有模块隐藏实现细节
将检测逻辑封装到单独文件,通过Dart的可见性控制隐藏脏话列表:
- 创建
lib/profanity_detector.dart文件:
library profanity_detector; // 私有列表,仅当前文件可见 final List<String> _profaneWords = [ 'كسمك', 'بنت الشرموطة', ... ]; // 对外暴露的检测方法 bool hasArabicProfanity(String input) { for (String word in _profaneWords) { if (input.contains(word)) { return true; } } return false; }
- 在其他文件中导入使用:
import 'package:your_app/profanity_detector.dart'; // 直接调用方法,看不到内部的脏话列表 bool hasBadWords = hasArabicProfanity(userInput);
内容的提问来源于stack exchange,提问作者Younis
相关产品推荐
相关产品推荐

