【发布时间】:2022-01-12 21:47:12
【问题描述】:
我正在尝试将 JSON 数据从 URL 显示到我的 Flutter 应用程序,但尚未找到任何解决方案。因为我有错误:
[LateInitializationError: 字段 '_userData@577066488' 尚未初始化]
如何在 Flutter 的 ListView 中显示这些数据?
这是我完整的 Flutter 项目:
网址解析:
http://jsonplaceholder.typicode.com/users
Main.dart
import 'package:flutter/material.dart';
import 'json_parse_demo.dart';
void main() {
runApp(const HomeApp());
}
class HomeApp extends StatelessWidget {
const HomeApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: JsonParseDemo(),
);
}
}
users.dart
// To parse this JSON data, do
//
// final users = usersFromJson(jsonString);
// ignore_for_file: file_names
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
User({
required this.user,
});
List<UserElement> user;
factory User.fromJson(Map<String, dynamic> json) => User(
user: List<UserElement>.from(
json["User"].map((x) => UserElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"User": List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class UserElement {
UserElement({
required this.id,
required this.name,
required this.username,
required this.email,
required this.address,
required this.phone,
required this.website,
required this.company,
});
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
factory UserElement.fromJson(Map<String, dynamic> json) => UserElement(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
Address({
required this.street,
required this.suite,
required this.city,
required this.zipcode,
required this.geo,
});
String street;
String suite;
String city;
String zipcode;
Geo geo;
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
Geo({
required this.lat,
required this.lng,
});
String lat;
String lng;
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
Company({
required this.name,
required this.catchPhrase,
required this.bs,
});
String name;
String catchPhrase;
String bs;
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
servicios.dart
import 'package:http/http.dart' as http;
import 'users.dart';
class Services {
//
static Uri uri = Uri.parse('http://jsonplaceholder.typicode.com/users');
static Future<List<User>> getUsers() async {
try {
final response = await http.get(uri);
if (200 == response.statusCode) {
final List<User> users = userFromJson(response.body) as List<User>;
return users;
} else {
return <User>[];
}
} catch (e) {
return <User>[];
}
}
}
json_parse_demo.dart
// ignore_for_file: unnecessary_null_comparison
import 'package:flutter/material.dart';
import 'users.dart';
import 'servicios.dart';
class JsonParseDemo extends StatefulWidget {
//
const JsonParseDemo({Key? key}) : super(key: key);
@override
_JsonParseDemoState createState() => _JsonParseDemoState();
}
class _JsonParseDemoState extends State<JsonParseDemo> {
//
late List<User> _users;
// late bool _loading;
bool _loading = true;
@override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: null == _users ? 0 : _users.length,
itemBuilder: (context, index) {
UserElement user = _users[index] as UserElement;
return ListTile(
title: Text(user.name),
subtitle: Text(user.email),
);
},
),
),
);
}
}
【问题讨论】: