Flutter日语词典查询插件unofficial_jisho_api的使用
Flutter日语词典查询插件unofficial_jisho_api的使用
插件介绍
unofficial_jisho_api
是一个用于查询日语词汇和汉字的Flutter插件。它提供了多种搜索和解析功能,包括单词/短语搜索、汉字搜索、示例句子搜索等。
以下是该插件的一些基本用法示例:
1. 单词/短语搜索(由官方Jisho API提供)
此功能返回与官方 Jisho.org API 相同的结果。
import 'package:unofficial_jisho_api/api.dart' as jisho;
void main() async {
// 搜索包含“日”的单词或短语
jisho.searchForPhrase('日').then((result) {
// 处理结果
print(result);
});
}
2. 汉字搜索
此功能可以搜索汉字的相关信息,如笔画数、读音等。
import 'dart:convert' show jsonEncode;
import 'package:unofficial_jisho_api/api.dart' as jisho;
void main() async {
await jisho.searchForKanji('語').then((result) {
print('找到:${result.found}');
final data = result.data;
if (data != null) {
print('汉字:${data.kanji}');
print('学习年级:${data.taughtIn}');
print('JLPT等级:${data.jlptLevel}');
print('新闻频率排名:${data.newspaperFrequencyRank}');
print('笔画数:${data.strokeCount}');
print('含义:${data.meaning}');
print('训读:${jsonEncode(data.kunyomi)}');
print('训读示例:${jsonEncode(data.kunyomiExamples[0])}');
print('音读:${jsonEncode(data.onyomi)}');
print('音读示例:${jsonEncode(data.onyomiExamples[0])}');
print('部首:${jsonEncode(data.radical)}');
print('组成部分:${jsonEncode(data.parts)}');
print('笔顺图:${data.strokeOrderDiagramUri}');
print('笔顺SVG:${data.strokeOrderSvgUri}');
print('笔顺GIF:${data.strokeOrderGifUri}');
print('Jisho链接:${data.uri}');
}
});
}
输出示例:
找到:true
汉字:語
学习年级:grade 2
JLPT等级:N5
新闻频率排名:301
笔画数:14
含义:word, speech, language
训读:["かた.る","かた.らう"]
训读示例:{"example":"語る","reading":"かたる","meaning":"to talk about, to speak of, to tell, to narrate, to recite, to chant, to indicate, to show"}
音读:["ゴ"]
音读示例:{"example":"語","reading":"ゴ","meaning":"language, word"}
部首:{"symbol":"言","forms":["訁"],"meaning":"speech"}
组成部分:["五","口","言"]
笔顺图:https://classic.jisho.org/static/images/stroke_diagrams/35486_frames.png
笔顺SVG:https://d1w6u4xc3l95km.cloudfront.net/kanji-2015-03/08a9e.svg
笔顺GIF:https://raw.githubusercontent.com/mistval/kanji_images/master/gifs/8a9e.gif
Jisho链接:https://jisho.org/search/%E8%AA%9E%23kanji
3. 示例句子搜索
此功能可以搜索包含特定单词的示例句子。
import 'dart:convert' show jsonEncode;
import 'package:unofficial_jisho_api/api.dart' as jisho;
void main() async {
await jisho.searchForExamples('日').then((result) {
print('Jisho链接:${result.uri}');
print('');
for (var i = 0; i < 3; i++) {
var example = result.results[i];
print(example.kanji);
print(example.kana);
print(example.english);
print(jsonEncode(example.pieces));
print('');
}
});
}
输出示例:
Jisho链接:https://jisho.org/search/%E6%97%A5%23sentences
日本人ならそんなことはけっしてしないでしょう。
にほんじんならそんなことはけっしてしないでしょう。
A Japanese person would never do such a thing.
[{"lifted":"にほんじん","unlifted":"日本人"},{"lifted":null,"unlifted":"なら"},{"lifted":null,"unlifted":"そんな"},{"lifted":null,"unlifted":"こと"},{"lifted":null,"unlifted":"は"},{"lifted":null,"unlifted":"けっして"},{"lifted":null,"unlifted":"しない"},{"lifted":null,"unlifted":"でしょう"}]
今日はとても暑い。
きょうはとてもあつい。
It is very hot today.
[{"lifted":"きょう","unlifted":"今日"},{"lifted":null,"unlifted":"は"},{"lifted":null,"unlifted":"とても"},{"lifted":"あつ","unlifted":"暑い"}]
日本には美しい都市が多い。例えば京都、奈良だ。
にほんにはうつくしいとしがおおい。たとえばきょうと、奈良だ。
Japan is full of beautiful cities. Kyoto and Nara, for instance.
[{"lifted":"にほん","unlifted":"日本"},{"lifted":null,"unlifted":"には"},{"lifted":"うつく","unlifted":"美しい"},{"lifted":"とし","unlifted":"都市"},{"lifted":null,"unlifted":"が"},{"lifted":"おお","unlifted":"多い"},{"lifted":"たと","unlifted":"例えば"},{"lifted":"きょうと","unlifted":"京都"},{"lifted":null,"unlifted":"だ"}]
4. 单词/短语抓取
此功能可以从Jisho.org的页面抓取数据,获取一些官方API没有的数据,如JLPT等级和词性。
import 'dart:convert';
import 'package:unofficial_jisho_api/api.dart' as jisho;
final JsonEncoder encoder = JsonEncoder.withIndent(' ');
void main() async {
await jisho.scrapeForPhrase('谷').then((data) {
print(encoder.convert(data));
});
}
输出示例:
{
"found": true,
"query": "谷",
"data": {
"uri": "https://jisho.org/word/%E8%B0%B7",
"tags": [
"Common word",
"JLPT N3",
"Wanikani level 5"
],
"meanings": [
{
"seeAlsoTerms": [],
"sentences": [],
"definition": "valley",
"supplemental": [],
"definitionAbstract": null,
"tags": []
},
{
"seeAlsoTerms": [],
"sentences": [],
"definition": "Valley",
"supplemental": [],
"definitionAbstract": "In geology, a valley or dale is a depression with predominant extent in one direction. A very deep river valley may be called a canyon or gorge. The terms U-shaped and V-shaped are descriptive terms of geography to characterize the form of valleys. Most valleys belong to one of these two main types or a mixture of them, (at least) with respect of the cross section of the slopes or hillsides.",
"tags": []
}
],
"otherForms": [
{
"kanji": "渓",
"kana": "たに"
},
{
"kanji": "谿",
"kana": "たに"
}
],
"audio": [
{
"uri": "https://d1vjc5dkcd3yh2.cloudfront.net/audio/b9ff4f25c7a20f0f39131b3e3db0cd19.mp3",
"mimetype": "audio/mpeg"
},
{
"uri": "https://d1vjc5dkcd3yh2.cloudfront.net/audio_ogg/b9ff4f25c7a20f0f39131b3e3db0cd19.ogg",
"mimetype": "audio/ogg"
}
],
"notes": []
}
}
5. 解析HTML字符串
你可以自己提供从Jisho获得的HTML响应。这在需要使用CORS代理时很有用。
解析汉字页面HTML
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:unofficial_jisho_api/parser.dart' as jisho_parser;
final JsonEncoder encoder = JsonEncoder.withIndent(' ');
const String searchKanji = '車';
final String searchURI = jisho_parser.uriForKanjiSearch(searchKanji);
void main() async {
await http.get(searchURI).then((result) {
final parsedResult = jisho_parser.parseKanjiPageData(result.body, searchKanji);
final data = parsedResult.data;
if (data != null) {
print('JLPT等级:${data.jlptLevel}');
print('笔画数:${data.strokeCount}');
print('含义:${data.meaning}');
}
});
}
解析示例页面HTML
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:unofficial_jisho_api/parser.dart' as jisho_parser;
final JsonEncoder encoder = JsonEncoder.withIndent(' ');
const String searchExample = '保護者';
final String searchURI = jisho_parser.uriForExampleSearch(searchExample);
void main() async {
await http.get(searchURI).then((result) {
final parsedResult = jisho_parser.parseExamplePageData(result.body, searchExample);
print('英文:${parsedResult.results[0].english}');
print('汉字 ${parsedResult.results[0].kanji}');
print('假名:${parsedResult.results[0].kana}');
});
}
解析短语页面HTML
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:unofficial_jisho_api/parser.dart' as jisho_parser;
final JsonEncoder encoder = JsonEncoder.withIndent(' ');
const String searchExample = '保護者';
final String searchURI = jisho_parser.uriForPhraseScrape(searchExample);
void main() async {
await http.get(searchURI).then((result) {
final parsedResult = jisho_parser.parsePhrasePageData(result.body, searchExample);
print(encoder.convert(parsedResult));
});
}
更多关于Flutter日语词典查询插件unofficial_jisho_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter日语词典查询插件unofficial_jisho_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用unofficial_jisho_api
插件来实现日语词典查询功能的代码示例。这个插件允许你访问Jisho API,一个非官方的日语词典API。
首先,确保你的Flutter项目已经创建好了。如果没有,请使用以下命令创建一个新的Flutter项目:
flutter create my_japanese_dictionary
cd my_japanese_dictionary
然后,在你的pubspec.yaml
文件中添加unofficial_jisho_api
依赖:
dependencies:
flutter:
sdk: flutter
unofficial_jisho_api: ^最新版本号 # 请替换为实际最新版本号
运行flutter pub get
来安装依赖。
接下来,修改你的main.dart
文件,实现一个简单的日语词典查询界面。以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/unofficial_jisho_api.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Japanese Dictionary',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DictionaryScreen(),
);
}
}
class DictionaryScreen extends StatefulWidget {
@override
_DictionaryScreenState createState() => _DictionaryScreenState();
}
class _DictionaryScreenState extends State<DictionaryScreen> {
final _controller = TextEditingController();
String _result = '';
void _search() async {
setState(() {
_result = 'Loading...';
});
try {
final jisho = Jisho();
final response = await jisho.search(_controller.text);
if (response.data!.length > 0) {
final entry = response.data!.first;
_result = entry.japanese![0].reading! + ': ' + entry.englishDefinitions!.join(', ');
} else {
_result = 'No results found.';
}
} catch (e) {
_result = 'Error: $e';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Japanese Dictionary'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextField(
controller: _controller,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Search for a word',
suffixIcon: IconButton(
icon: Icon(Icons.search),
onPressed: _search,
),
),
),
SizedBox(height: 16),
Text(
_result,
style: TextStyle(fontSize: 18),
),
],
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
这个示例展示了如何使用unofficial_jisho_api
插件来查询日语单词,并在UI中显示查询结果。以下是代码的主要部分解释:
- 依赖项:在
pubspec.yaml
文件中添加unofficial_jisho_api
依赖。 - UI布局:使用
Scaffold
、AppBar
、TextField
和Text
等Flutter组件来构建简单的查询界面。 - 查询功能:定义一个
_search
函数,使用Jisho
类的search
方法来查询用户输入的单词,并更新UI显示结果。 - 状态管理:使用
StatefulWidget
和TextEditingController
来管理UI状态和文本输入。
运行这个Flutter应用,你应该能够输入日语单词并查看其英文定义。
请注意,unofficial_jisho_api
插件的API可能会随时间变化,因此请参考其官方文档以获取最新和最准确的使用说明。