【发布时间】:2019-10-05 08:33:04
【问题描述】:
首先,我是 Flutter、dart 和 StackOverflow 的新手。
我只是想体验一些关于颤振和解析 json 文件的初步见解。 但是我收到一个错误,即在 null 上调用了 getter 'visible'。
通过 Flutter 中的调试模式,我可以清楚地看到 API 提供的所有数据,但前端什么也没显示。 只是调试控制台中提到的错误。
这是非常简单的代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'JSON',
home: Scaffold(
appBar: AppBar(
title: Text('JSON'),
),
body: Container(
child: FutureBuilder<List<User>>(
future: fetchListUser(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
List<User> users = snapshot.data;
return ListView(
children: users.map((user) {
Text('UserName: ${user.username}');
}).toList(),
);
} else {
return CircularProgressIndicator();
}
}),
),
),
);
}
}
Future<List<User>> fetchListUser() async {
final response = await http.get('https://jsonplaceholder.typicode.com/users');
if (response.statusCode == 200) {
List users = json.decode(response.body);
return users.map((user) => User.fromJson(user)).toList();
} else
throw Exception('Failed to Load Users');
}
class User {
final int id;
final String name, username, email, phone, website;
final Adresse adress;
final Company company;
User({
this.id,
this.name,
this.adress,
this.company,
this.email,
this.phone,
this.username,
this.website,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
adress: Adresse.fromJson(json['address']),
company: Company.fromJson(json['company']),
email: json['email'],
id: json['id'],
name: json['name'],
phone: json['phone'],
username: json['username'],
website: json['website'],
);
}
}
class Adresse {
final String street, suite, zipcide;
final Geo geo;
Adresse({this.geo, this.street, this.suite, this.zipcide});
factory Adresse.fromJson(Map<String, dynamic> json) {
return Adresse(
geo: Geo.fromJson(json['geo']),
street: json['street'],
suite: json['suite'],
zipcide: json['zipcode'],
);
}
}
class Geo {
final String lat, lng;
Geo({this.lat, this.lng});
factory Geo.fromJson(Map<String, dynamic> json) {
return Geo(
lat: json['lat'],
lng: json['lng'],
);
}
}
class Company {
final String name;
final String catchPhrase;
final String bs;
Company({this.bs, this.catchPhrase, this.name});
factory Company.fromJson(Map<String, dynamic> json) {
return Company(
bs: json['bs'],
catchPhrase: json['catchPhrase'],
name: json['name'],
);
}
}
它实际上只是为 json 结构构建了一些类,然后我只想输出一些东西。
有人可以帮我吗? :)
谢谢!
【问题讨论】:
-
检查这个网址。答案在here。在您的情况下,缺少 Listview 的 itemCount 参数。