Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been having trouble understanding how to correctly list of all the items from the API call, I have now made it to display the first from the list of the API, by adding the index [0] after the API response. I realize I can do that with the itemCount which I currently had it set at 1 since I can't seem to comprehend how to use the .length option that lists all of the item from the API. Here is the code:

API CALL:

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');
  }
}

THE JOB MODEL:

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'],
    );
  }
}

AND THE WIDGET WHERE IT IS RENDERED:

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,
        ),
      ],
    );
  }
}

Do you I need to make a list out of the returned API response first and then display it's length?

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Try changing this..

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');
  }
}

then..

Future<List<JobData>> futureJobs;

inside ListView

itemCount: futureJobs.length,

then take each job from futureJobs list using index and show in ListView()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...