Flutter 中的列表视图
List View in Flutter
我一直无法理解如何正确列出 API 调用中的所有项目,现在我已经成功地显示了 API 列表中的第一个项目,通过在 API 响应后添加索引 [0]。我意识到我可以使用我目前将其设置为 1 的 itemCount 来做到这一点,因为我似乎无法理解如何使用列出 API 中所有项目的 .length 选项。这是代码:
API 呼叫:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:practice/models/jobs.dart';
Future<JobData> fetchJobs() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return JobData.fromJson(jsonDecode(response.body)[0]);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
工作模型:
import 'package:flutter/foundation.dart';
class JobData extends ChangeNotifier {
final int userId;
final int id;
final String title;
final String body;
JobData({this.userId, this.id, this.title, this.body});
factory JobData.fromJson(Map<String, dynamic> json) {
return JobData(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
及其呈现的小部件:
import 'package:flutter/material.dart';
import 'package:practice/models/jobs.dart';
import 'package:provider/provider.dart';
import 'package:practice/services/api_calls.dart';
class JobList extends StatefulWidget {
@override
_JobListState createState() => _JobListState();
}
class _JobListState extends State<JobList> {
Future<JobData> futureJobs;
@override
void initState() {
super.initState();
futureJobs = fetchJobs();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'Today',
),
SizedBox(
height: 12.0,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12.0),
topRight: Radius.circular(12.0),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
'Jobs #1',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
FlatButton(
textColor: Colors.blue[700],
minWidth: 0,
child: Text('View'),
onPressed: () {
},
),
],
),
),
Container(
padding: EdgeInsets.all(18.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12.0),
bottomRight: Radius.circular(12.0),
),
),
child: Consumer<JobData>(
builder: (context, jobData, child) {
return SizedBox(
height: 200,
child: FutureBuilder<JobData>(
future: futureJobs,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: 1,
itemBuilder: (context, index) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('${snapshot.data.userId}',
style: TextStyle(color: Colors.black),
Text(
'${snapshot.data.id}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.title}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.body}',
style: TextStyle(color: Colors.black),
),
],
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
},
),
),
SizedBox(
height: 16.0,
),
],
);
}
}
是否需要先从返回的 API 响应中列出一个列表,然后显示它的长度?
提前致谢!
尝试改变这个..
Future<List<JobData>> fetchJobs() async {
List<JobData> jobs = new List();
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var jobsJson = jsonDecode(response.body);
for(int i = 0; i < jobsJson.length; i++) {
jobs.add(JobData.fromJson(jobsJson[i]));
}
return jobs;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
然后..
Future<List<JobData>> futureJobs;
在 ListView 内部
itemCount: futureJobs.length,
然后使用索引从 futureJobs
列表中获取每个作业并显示在 ListView()
中
我一直无法理解如何正确列出 API 调用中的所有项目,现在我已经成功地显示了 API 列表中的第一个项目,通过在 API 响应后添加索引 [0]。我意识到我可以使用我目前将其设置为 1 的 itemCount 来做到这一点,因为我似乎无法理解如何使用列出 API 中所有项目的 .length 选项。这是代码:
API 呼叫:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:practice/models/jobs.dart';
Future<JobData> fetchJobs() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return JobData.fromJson(jsonDecode(response.body)[0]);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
工作模型:
import 'package:flutter/foundation.dart';
class JobData extends ChangeNotifier {
final int userId;
final int id;
final String title;
final String body;
JobData({this.userId, this.id, this.title, this.body});
factory JobData.fromJson(Map<String, dynamic> json) {
return JobData(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
及其呈现的小部件:
import 'package:flutter/material.dart';
import 'package:practice/models/jobs.dart';
import 'package:provider/provider.dart';
import 'package:practice/services/api_calls.dart';
class JobList extends StatefulWidget {
@override
_JobListState createState() => _JobListState();
}
class _JobListState extends State<JobList> {
Future<JobData> futureJobs;
@override
void initState() {
super.initState();
futureJobs = fetchJobs();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'Today',
),
SizedBox(
height: 12.0,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12.0),
topRight: Radius.circular(12.0),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
'Jobs #1',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
FlatButton(
textColor: Colors.blue[700],
minWidth: 0,
child: Text('View'),
onPressed: () {
},
),
],
),
),
Container(
padding: EdgeInsets.all(18.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12.0),
bottomRight: Radius.circular(12.0),
),
),
child: Consumer<JobData>(
builder: (context, jobData, child) {
return SizedBox(
height: 200,
child: FutureBuilder<JobData>(
future: futureJobs,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: 1,
itemBuilder: (context, index) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('${snapshot.data.userId}',
style: TextStyle(color: Colors.black),
Text(
'${snapshot.data.id}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.title}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.body}',
style: TextStyle(color: Colors.black),
),
],
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
},
),
),
SizedBox(
height: 16.0,
),
],
);
}
}
是否需要先从返回的 API 响应中列出一个列表,然后显示它的长度?
提前致谢!
尝试改变这个..
Future<List<JobData>> fetchJobs() async {
List<JobData> jobs = new List();
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var jobsJson = jsonDecode(response.body);
for(int i = 0; i < jobsJson.length; i++) {
jobs.add(JobData.fromJson(jobsJson[i]));
}
return jobs;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
然后..
Future<List<JobData>> futureJobs;
在 ListView 内部
itemCount: futureJobs.length,
然后使用索引从 futureJobs
列表中获取每个作业并显示在 ListView()