json - Flutter api使用
问题描述
我对这个行业很陌生,不能使用 api。无论我看多少培训内容,当我尝试自己尝试时都会遇到错误。我无法摆脱这个恶性循环。我将示例代码片段留在下面。请向我解释我应该如何看待这个行业。谢谢
用户模型
class User{
String userId;
int id;
String title;
String body;
User({this.userId,this.id,this.title,this.body});
factory User.fromJson(Map<String, dynamic> parsedJson){
return User(
userId: parsedJson["userId"],
id: parsedJson["id"],
title: parsedJson["title"],
body: parsedJson["body"]
);
}
}
用户服务
Future getUser() async{
var response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));
final jsonDecode = json.decode(response.body);
var user = User.fromJson(jsonDecode);
return user;
}
主屏幕
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
User user = User();
@override
void initState() {
super.initState();
getUser().then((value) {
setState(() {
user = value;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: user == null
? CircularProgressIndicator()
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("${user?.id}"),
Text("${user?.title}"),
Text("${user?.userId}"),
Text("${user?.body}"),
],
),
),
),
);
}
}
我在哪里犯错?感谢您的解释性回答。
解决方案
我试过你的代码,它抛出了这个异常:
Unhandled Exception: type 'int' is not a subtype of type 'String?'
在课堂上的这一行User
:
String userId;
userId
在 json 文件中是一个 int,而不是一个字符串。
将该行更改为:
int userId;
它应该工作。
推荐阅读
- ios - iOS 架构:具有许多选项的对象
- sqlite - ionic3 SQLite 单元测试
- powerbi-embedded - 禁用 Power BI Embedded 报表的编辑模式
- django - 在 Google App Engine 标准环境中使用 PostgreSQL 和 Django
- replication - MySQL 5.7.23 和 5.7.24 上的冻结复制
- sql - 将列拆分为三列的新行
- python - 将数据帧与 MultiIndex 相加
- r - 清理 R 中的数据:需要 TRUE/FALSE 的错误缺失值
- c# - 将此代码转换为使用带有批处理模式的 Microsoft Graph
- pdf - 是否可以减少 GhostScript 内存?