我尝试呈现服务器请求的结果,其格式为json数据。
这是API返回的json。
{
id: 1,
name: Nhel Theavuth,
email: info@theavuth.me,
username: theavuth,
avatar: null,
phone_number: null,
token:
}
用户模型:
import 'package:flutter/foundation.dart';
class User with ChangeNotifier {
int id;
String fullName;
String phoneNumber;
String email;
String username;
String avatar;
String token;
User({
this.id,
this.fullName,
this.phoneNumber,
this.email,
this.username,
this.avatar,
this.token
});
factory User.fromJson(dynamic json) {
return User(
id : json['id'],
fullName : json['name'],
phoneNumber: json['phone_number'],
email : json['email'],
username : json['username'],
avatar : json['avatar'],
token : json['token']
);
}
Map<String, dynamic> toJson() => {
'id' : id,
'name' : fullName,
'phone_number': phoneNumber,
'email' : email,
'username' : username,
'avatar' : avatar,
'token' : token
};
}
此代码可从服务器调用dataJson。
void getProfileData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String _token = prefs.getString('token');
Map<String, dynamic> responseData = await _userProvider.userProfile({'token': _token});
print(responseData['data']);
List<User> profileData = (responseData['data'].toList()).map((parsedJson) => User.fromJson(parsedJson)).toList();
setState(() {
this.userProfile = profileData;
});
}
将上述json呈现给用户模型后,此错误消息。
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
任何人都可以帮忙吗? 预先感谢
答案 0 :(得分:1)
我需要有关正在发生的事情的更多信息,添加代码。但是似乎您需要调用private/
才能从JSON结果中获取列表,因为Dart将json作为Map管理。
答案 1 :(得分:1)
您可以在下面复制粘贴运行完整代码
假设您的json字符串是
String jsonString = '''
{
"id": 1,
"name": "Nhel Theavuth",
"email": "info@theavuth.me",
"username": "theavuth",
"avatar": null,
"phone_number": null,
"token": ""
}
''';
第1步:修改User.fromJson
,您可以在完整代码中看到User
定义
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
name: json["name"],
email: json["email"],
username: json["username"],
avatar: json["avatar"],
phoneNumber: json["phone_number"],
token: json["token"],
);
步骤2:使用函数userFromJson
解析json字符串
User userFromJson(String str) => User.fromJson(json.decode(str));
...
User user = userFromJson(jsonString);
print(user.name);
输出
I/flutter (12738): Nhel Theavuth
完整代码
import 'package:flutter/material.dart';
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
int id;
String name;
String email;
String username;
dynamic avatar;
dynamic phoneNumber;
String token;
User({
this.id,
this.name,
this.email,
this.username,
this.avatar,
this.phoneNumber,
this.token,
});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
name: json["name"],
email: json["email"],
username: json["username"],
avatar: json["avatar"],
phoneNumber: json["phone_number"],
token: json["token"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"email": email,
"username": username,
"avatar": avatar,
"phone_number": phoneNumber,
"token": token,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
String jsonString = '''
{
"id": 1,
"name": "Nhel Theavuth",
"email": "info@theavuth.me",
"username": "theavuth",
"avatar": null,
"phone_number": null,
"token": ""
}
''';
User user = userFromJson(jsonString);
print(user.name);
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}