【发布时间】:2021-04-09 03:57:49
【问题描述】:
我在实体用户中有一个组织列表,我想做的是读取列表的字段(json 类型)并将其显示在 Futurebuilder 中尝试过这是组织 DTO:
import 'dart:convert';
Organizations organizations(String str) =>
Organizations.fromJson(json.decode(str));
String OrganizationsToJson(Organizations data) => json.encode(data.tojson());
class Organizations{
// ignore: non_constant_identifier_names
Organizations({this.organizationId, this.role, this.createdAt, this.assignmentId});
// ignore: non_constant_identifier_names
String organizationId;
String role;
String createdAt;
String assignmentId;
factory Organizations.fromJson(Map<String, dynamic> json){
return Organizations(organizationId: json['organizationId'] , role: json["role"] , createdAt: json["createdAt"] , assignmentId: json["assignmentId"]);
}
Map<String, dynamic> tojson()=>{
"organizationId": organizationId,
"role" : role,
"createdAt" : createdAt,
"assignmentId" : assignmentId,
};
//String get organizationId => organizationId;
//String get role => role;
//DateTime get createdAt => createdAt ;
//String get assignmentId => assignmentId;
String get organizationID {
return organizationId;
}
String get userRole => role;
String get creationDate => createdAt;
String get assignmentid => assignmentId;
}
用户 DTO:
import 'package:helium_app/models/organizations.dart';
import 'dart:convert';
User user(String str) =>
User.fromJson(json.decode(str));
String UserToJson(User data) => json.encode(data.tojson());
class User{
// ignore: non_constant_identifier_names
User({this.email, this.firstname, this.id, this.lastname, this.organizations});
String email;
String firstname;
String id;
String lastname;
// ignore: non_constant_identifier_names
//final DateTime creation_date;
// ignore: non_constant_identifier_names
//final DateTime last_updated_date;
// ignore: non_constant_identifier_names
//final DateTime last_login_date;
List<Organizations> organizations;
factory User.fromJson(Map<String, dynamic> json){
return User(
email: json['email'],
firstname: json['firstname'],
id: json['id'],
lastname: json['lastname'],
//creation_date: json['creation-date'],
// last_updated_date: json['last-updated-date'],
// last_login_date: json['last-login-date'],
organizations: (json['organizations'] as List).
map((p) => Organizations.fromJson(p)).toList()
);
}
Map<String, dynamic> tojson()=>{
"email": email,
"firstname" : firstname,
"lastname" : lastname,
"organizations" : organizations,
};
String get userEmail => email;
String get userFirstName => firstname;
String get userLastName => lastname;
List<Organizations> get userOrganizations => organizations;
}
这是用于解析数据的函数:
Future<User> fetchUser() async {
final response = await http.get('http://10.0.2.2:8093/user/v1/users/cc535e96-d6ec-4334-9588-890f12122254');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return User.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load user');
}
}
我尝试了这种方法从列表中获取我想要的字段(角色和创建日期):
Future<User> futureUser;
get index => null;
ListTile(
contentPadding: EdgeInsets.all(0),
title: Text("organisation"),
subtitle: Text(snapshot.data.organizations[index].role)
)],
在futurebuilder ofc和widget build方法中, 但我只得到这个错误:
这是整个例子:
class Profile extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _ProfileHomeState();
}
}
Future<User> fetchUser() async {
final response = await http.get('http://10.0.2.2:8093/user/v1/users/cc535e96-d6ec-4334-9588-890f12122254');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return User.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load user');
}
}
class _ProfileHomeState extends State<Profile> {
Future<User> futureUser;
get index => null;
@override
void initState() {
super.initState();
futureUser = fetchUser();
}
//getUserInformation() async{
//var response = await http.get('http://localhost:8093/user/v1/users/2e48ff17-b327-4db6-a60b-97a9fcc20362');
//var jsonData = json.decode(response.body);
//firstname = jsonData['firstname'];
// lastname = jsonData['lastname'];
//email = jsonData['email'];
//setState(() {
//var jsonData = json.decode(response.body);
//firstname = jsonData['firstname'];
//lastname = jsonData['lastname'];
//email = jsonData['email'];
//});
// print (firstname);
//print (lastname);
// print (email);
// }
//static final String path = "lib/screens/profile/profile_home.dart";
final image = 'assets/images/user_profile.png';
@override
Widget build(BuildContext context){
return Scaffold(
body: SingleChildScrollView(
child : FutureBuilder<User>(
future: futureUser,
// ignore: missing_return
builder:(context, snapshot){
if (snapshot.hasData) {
return Stack(
children: [
SizedBox(
height: 250,
width: double.infinity,
//child: Image.asset(image, fit: BoxFit.cover,),
child: Container(
height: 360,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(50.0), bottomRight: Radius.circular(50.0)),
gradient: LinearGradient(
colors: [kPrimaryColor,color2],
begin: Alignment.topLeft,
end: Alignment.bottomRight
)
),
),
),
Container(
margin: EdgeInsets.fromLTRB(16.0, 200.0, 16.0, 16.0),
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.only(top: 16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 96.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data.firstname, style: Theme.of(context).textTheme.title,),
ListTile(
contentPadding: EdgeInsets.all(0),
title: Text("organisation"),
subtitle: Text(snapshot.data.organizations[index].role)
)],
),
),
SizedBox(height: 10.0),
],
),
),
Container(
height: 80,
width: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: AssetImage(image),
fit: BoxFit.cover
)
),
margin: EdgeInsets.only(left: 16.0),
),
],
),
SizedBox(height: 20.0),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5.0),
),
child: Column(
children: <Widget>[
ListTile(title: Text("User information"),),
Divider(),
ListTile(
title: Text("Email"),
subtitle: Text(snapshot.data.email),
leading: Icon(Icons.email,color: kPrimaryColor),
),
ListTile(
title: Text("Organisation"),
subtitle: Text("https://www.littlebutterfly.com"),
leading: Icon(Icons.people,color: kPrimaryColor),
),
ListTile(
title: Text("Joined Date"),
subtitle: Text(snapshot.data.organizations[index].createdAt),
leading: Icon(Icons.calendar_view_day,color: kPrimaryColor,),
),
],
),
)
],
),
),
AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
)
],
);
}
else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
}
),
),
);
}
}
如果有人能帮忙解决这个问题或知道哪里出了问题,我将不胜感激
【问题讨论】:
-
你能分享一段你的json响应吗?您的代码中的链接无法访问
-
如果您也可以将错误日志粘贴到调试控制台中会很有帮助。