我在实体用户中有一个组织列表,我要做的是读取列表的字段(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 和小部件构建方法中, 但我只收到此错误:
这是整个例子:
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();
}
),
),
);
}
}
如果有人可以帮助解决这个问题或知道出了什么问题,我将不胜感激
答案 0 :(得分:0)
organization_model.dart
class OrganizationModel {
String _id, _role, _createdAt, _assignmentId;
OrganizationModel.fromJson(Map<String, dynamic> data) {
_id = data['organizationId'];
_role = data['role'];
_createdAt = data['createdAt'];
_assignmentId = data['assignmentId'];
}
String get id => _id;
String get userRole => _role;
String get creationDate => _createdAt;
String get assignmentId => _assignmentId;
String show() => '''
ID : $_id
Role : $_role
Created At : $_createdAt
Assignment ID : $_assignmentId
''';
}
user_model.dart
import 'package:read_json/models/organization_model.dart';
class UserModel {
String _id, _firstName, _lastName, _email;
var _organizations = List<OrganizationModel>();
UserModel.fromJson(Map<String, dynamic> data) {
_id = data['id'];
_firstName = data['firstname'];
_lastName = data['lastname'];
_email = data['email'];
(data['organizations'] as List).forEach((e) => _organizations.add(OrganizationModel.fromJson(e)));
}
String get id => _id;
String get firstName => _firstName;
String get lastName => _lastName;
String get email => _email;
List<OrganizationModel> get organizations => _organizations;
String show() => '''
ID : $_id
First Name : $_firstName
Last Name : $_lastName
eMail : $_email
Organizations :
${_organizations.fold("", (s, e) => s + e.show())}
''';
}
net_service.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:read_json/models/user_model.dart';
const userData = '''
{
"data": {
"id": "5",
"firstname": "Billiardo",
"lastname": "Aragorn",
"email": "nobody@arcadia.net",
"organizations": [
{
"organizationId": "002",
"role": "noob",
"createdAt" : "1234343535",
"assignmentId" : "2346757"
},
{
"organizationId": "003",
"role": "pro",
"createdAt" : "234324354352",
"assignmentId" : "3245546435"
}
]
}
}
''';
class NetService {
static Future fetchJsonData(String url) {
return
http.get(url)
.then((response) => response?.statusCode == 200 ? jsonDecode(response.body) : null)
.catchError((err) => print(err));
}
static Future<UserModel> fetchUser() {
return fetchJsonData('http://10.0.2.2:8093/user/v1/users/cc535e96-d6ec-4334-9588-890f12122254')
.then((response) => (response != null) ? UserModel.fromJson(response['data']) : null)
.catchError((err) => print('OMFG!!! an error: $err'));
}
static Future<UserModel> fetchLocalUser() {
return Future<UserModel>.delayed(
Duration(seconds: 3),
() => UserModel.fromJson(jsonDecode(userData)['data']),
);
}
}
home_page.dart
import 'package:flutter/material.dart';
import 'package:read_json/models/user_model.dart';
import 'package:read_json/services/net_service.dart';
class HomePage extends StatelessWidget {
/* ---------------------------------------------------------------------------- */
const HomePage({Key key}) : super(key: key);
/* ---------------------------------------------------------------------------- */
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hi!'),
centerTitle: true,
),
body: FutureBuilder<UserModel>(
future: NetService.fetchLocalUser(),
builder: (context, snapshot) => snapshot.hasData
? Text(snapshot.data.show())
: snapshot.hasError
? Text('Something was wrong!: ${snapshot.error}')
: Text('Loading...'),
),
);
}
}