1

I am trying to parse an api in flutter. the asynchronous request delays the response which is shown by the progress indicator. but the progress indicator does not fade away after the response is fetched. it remains still on the screen.

how to change the state of the progress loader to listview.builder when the response is fetched?

this is my code.

    import 'dart:convert';

    import 'package:flutter/material.dart';

    import 'users.dart';
    import 'package:http/http.dart' as http;

    class HomePage extends StatefulWidget {
     @override
     _HomePageState createState() => _HomePageState();
    }

    class _HomePageState extends State<HomePage> {

    bool isLoading = false;

    List<Users> _users;
    Future<List<Users>> getUsers() async {
    var response = await http.get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    _users = usersFromJson(response.body);
    isLoading = true;

  }
  @override
  void initState() {
      setState(() {
        getUsers();
      });
  }


    @override
    Widget build(BuildContext context) {
     return Scaffold(
      appBar: AppBar(
       title: Text(isLoading ? "Parsed Json" : "Loading..."),
       backgroundColor: Colors.deepPurple,
      ),
       body: isLoading ? ListView.builder(
             itemCount: _users.length,
             itemBuilder: (BuildContext context,int index){
            return ListTile(
              leading: Image.network('https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80'),
              title:  Text(_users[index].name),
             );
         }) : Center(child: CircularProgressIndicator()),
        );
     }
    }
Arpit Todewale
  • 129
  • 2
  • 11

3 Answers3

1

Working code, try this

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isLoading = false;

  List<Users> _userList = [];

  Future<void> getUsers() async {
    isLoading = true;
    var response = await http
        .get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    var jsonResponse = jsonDecode(response.body);
    // print(jsonResponse);
    jsonResponse.forEach((data) {
      Users user = Users.fromMap(data);
      print(user);
      _userList.add(user);
    });
    isLoading = false;
  }

  @override
  void initState() {
    getUsers().then((value) => setState(() {}));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(isLoading ? "Loading..." : "Parsed Json"),
          backgroundColor: Colors.deepPurple,
        ),
        body: isLoading
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: _userList.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(_userList[index].name),
                  );
                }));
  }
}

class Users {
  int id;
  String name;
  String username;
  Users({
    this.id,
    this.name,
    this.username,
  });
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'username': username,
    };
  }

  factory Users.fromMap(Map<String, dynamic> map) {
    if (map == null) return null;

    return Users(
      id: map['id'],
      name: map['name'],
      username: map['username'],
    );
  }

  String toJson() => json.encode(toMap());

  factory Users.fromJson(String source) => Users.fromMap(json.decode(source));

  @override
  String toString() => 'Users(id: $id, name: $name, username: $username)';
}

Raine Dale Holgado
  • 2,932
  • 2
  • 17
  • 32
1

Check your _user != null instead of bool then show list otherwise indicator

Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40
Mr vd
  • 878
  • 1
  • 10
  • 19
0

void initState () method Called when this object is inserted into the tree. The framework will call this method exactly once for each State object it creates. so there is no need for setState in initState() method.

try set setState after the response, so

 @override
  void initState() {
    super.initState();
      getUsers();

  }



 Future<List<Users>> getUsers() async {
    isLoading = false;
    var response = await http.get(Uri.encodeFull('http://jsonplaceholder.typicode.com/users'));
    _users = usersFromJson(response.body);
    print(_users);
    setState(() {
      isLoading = true;
    });

    return _users;
  }
ajay
  • 808
  • 9
  • 18