为什么我的jsondecode()方法在flutter中抛出格式异常?
我已经学习 Flutter 移动开发有一段时间了,目前正在尝试构建一个单页文本翻译应用程序,以供练习。我尝试整合一个 Google 翻译 API。
由于我用来提取翻译结果 json 对象(Post 方法 HTTP 请求)的 jsonDecode() 方法中出现错误(格式异常),我在运行应用程序时遇到问题
这是我的主屏幕代码
import 'package:flutter/material.dart';
import '../models/input_model.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = TextEditingController();
final translation = Sentence();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Translation App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
////////////// Widget for the translation source text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)))),
)),
////////////////////////////////////////////////////////////////////
ElevatedButton(
onPressed: () {
Sentence.connectToAPI('en', 'de', textController.text); //static language option
setState(() {}); //input for testing
},
child: Text('Translate')),
////////////// Widget for the translation result text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: Text((translation.trans == null)
? 'no data'
: translation.trans.toString())),
],
),
),
);
}
}
这是出现问题的模型文件谎言:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Sentence {
Sentence({
this.trans,
this.orig,
this.backend,
});
String? trans;
String? orig;
int? backend;
factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
trans: json["trans"],
orig: json["orig"],
backend: json["backend"],
);
Map<String, dynamic> toJson() => {
"trans": trans,
"orig": orig,
"backend": backend,
};
static Future<Sentence> connectToAPI(
String from, String to, String text) async {
String pathURL =
'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
var response =
await http.post(Uri.parse(pathURL), headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'PostmanRuntime/7.29.0'
}, body: {
'sl': from,
'tl': to,
'q': text
});
var jsonObject = jsonDecode(response.body); //the exception error message pointed here
var textObject = (jsonObject as Map<String, dynamic>)['sentences'];
return Sentence.fromJson(textObject);
}
}
异常错误消息是:
FormatException(FormatException:意外字符(位于字符1)
^
我仍然是新手,这真的让我很困惑。我尝试在Google上搜索错误消息的解释,但仍然有很难理解这里的问题是什么?
I've been learning mobile development on Flutter for a while and currently trying to build a single-page text translation app, for exercise. I tried to integrate a Google Translate API.
I'm having trouble running the app due to an error (Format Exception) in the jsonDecode() method I use to extract the translation result json object (Post method HTTP request)
Here's my home screen code
import 'package:flutter/material.dart';
import '../models/input_model.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = TextEditingController();
final translation = Sentence();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Translation App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
////////////// Widget for the translation source text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)))),
)),
////////////////////////////////////////////////////////////////////
ElevatedButton(
onPressed: () {
Sentence.connectToAPI('en', 'de', textController.text); //static language option
setState(() {}); //input for testing
},
child: Text('Translate')),
////////////// Widget for the translation result text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: Text((translation.trans == null)
? 'no data'
: translation.trans.toString())),
],
),
),
);
}
}
And here's the model file where the problem lies:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Sentence {
Sentence({
this.trans,
this.orig,
this.backend,
});
String? trans;
String? orig;
int? backend;
factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
trans: json["trans"],
orig: json["orig"],
backend: json["backend"],
);
Map<String, dynamic> toJson() => {
"trans": trans,
"orig": orig,
"backend": backend,
};
static Future<Sentence> connectToAPI(
String from, String to, String text) async {
String pathURL =
'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
var response =
await http.post(Uri.parse(pathURL), headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'PostmanRuntime/7.29.0'
}, body: {
'sl': from,
'tl': to,
'q': text
});
var jsonObject = jsonDecode(response.body); //the exception error message pointed here
var textObject = (jsonObject as Map<String, dynamic>)['sentences'];
return Sentence.fromJson(textObject);
}
}
The exception error message was:
FormatException (FormatException: Unexpected character (at character 1)
^
I'm still a newbie and it really confuses me. I tried to search for the explanation of the error message on Google but still having a hard time understanding it. What seems to be the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论