Flutter 中的列表视图
Posted
技术标签:
【中文标题】Flutter 中的列表视图【英文标题】:List View in Flutter 【发布时间】:2021-04-16 08:44:36 【问题描述】:我一直无法理解如何正确列出 API 调用中的所有项目,现在我通过在 API 响应后添加索引 [0] 来显示 API 列表中的第一个项目.我意识到我可以使用我当前设置为 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 响应中列出一个列表,然后显示它的长度吗?
提前致谢!
【问题讨论】:
你想只显示第一份工作吗? @Shanto 我想显示我正在调用的 API 中的所有 100 个作业。 【参考方案1】:尝试改变这个..
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;
在列表视图中
itemCount: futureJobs.length,
然后使用索引从futureJobs
列表中获取每个作业并显示在ListView()
中
【讨论】:
效果很好,谢谢! :) 但我是对的吗?我必须首先从从 API 调用收到的数据中列出一个列表,然后在组件中显示它?这就是你所做的,对吧?以上是关于Flutter 中的列表视图的主要内容,如果未能解决你的问题,请参考以下文章