我正在构建一个应用程序,只是为了测试我的技能,但我面临着一个错误,在我的项目中导入JSON文件,这里是我的翻译代码,用于在我的应用程序中翻译ayah。文件位于assets/repository/translation.json.
import 'dart:convert';
import 'dart:io';
import 'package:islam_plus/models/translation_model.dart';
import 'package:quran/quran.dart' as quran;
class TranslationService {
final String _filePath = 'assets/repository/translation.json';
List<AyahTranslation> translationList = [];
Future<void> loadTranslations() async {
final jsonString = await File(_filePath).readAsString();
print(jsonString);
final jsonBody = jsonDecode(jsonString);
print(jsonBody);
final List<dynamic> quranList = jsonBody['quran'];
translationList = quranList
.map((dynamic item) => AyahTranslation.fromJson(item))
.toList();
}
List<AyahTranslation> getAyahTranslation(int surahNumber) {
final totalVerseCount = quran.getVerseCount(surahNumber);
int verseCount = 1;
final translationFiltered = translationList.where((translation) {
if (surahNumber == translation.chapter) {
verseCount++;
if (verseCount > totalVerseCount) {
verseCount = 1;
}
return true;
}
return false;
}).toList();
return translationFiltered;
}
String getRandomTranslation(int surahNumber, int verseNumber) {
final translationList = getAyahTranslation(surahNumber);
final translation = translationList.firstWhere(
(translation) => translation.verse == verseNumber,
orElse: () => AyahTranslation(
chapter: surahNumber,
verse: verseNumber,
text: 'Translation Not found'));
return translation.text;
}
}
这里是pubspec yaml
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/number_star.png
- assets/repository/translation.json
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
下面是主文件初始化状态
class _QuranPageState extends State<QuranPage> with TickerProviderStateMixin {
final service = QuranService();
late TabController _tabController;
TranslationService _translationService = TranslationService();
onTabChange(int index) {}
@override
void initState() {
_translationService.loadTranslations();
_tabController = TabController(length: 4, vsync: this);
super.initState();
}
这是我得到的错误
E/flutter (10333): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PathNotFoundException: Cannot open file, path = 'assets/repository/translation.json' (OS Error: No such file or directory, errno = 2)
应用程序运行良好,但当我点击一个surah看到翻译,我得到范围错误,我想错误是因为空列表,这是依赖于翻译文件。
1条答案
按热度按时间hi3rlvi21#
如果你想从资源中加载json,你不能将路径传递给
File
对象。试试这个:
也可以使用
rootBundle
: