juan manuel jimenez
juan manuel jimenez

Reputation: 11

Unable to display the user list in Flutter using FutureBuilder and Dio

I am trying to display a list of users in my Flutter application using FutureBuilder and the Dio library to make an HTTP request. However, the user list does not appear, and I am not sure what the problem is.

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:convert';

import 'package:larpland/model/user.dart';

class UsersList extends StatefulWidget {
  const UsersList({super.key});

  @override
  State<UsersList> createState() => _UsersListState();
}

class _UsersListState extends State<UsersList> {
  late Future<List<User>> futureUserList;

  @override
  void initState() {
    super.initState();
    futureUserList = fetchUserList();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<User>>(
      future: futureUserList,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(snapshot.data![index].name),
                subtitle: Text(snapshot.data![index].email),
              );
            },
          );
        } else if (snapshot.hasError) {
          return const Center(
            child: Text('Failed to load user list'),
          );
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
  }

  Future<List<User>> fetchUserList() async {
    final response = await Dio().get('https://10.0.2.2:8000/api/users');
    if (response.statusCode == 200) {
      return List<User>.from(jsonDecode(response.data).map((user) => User.fromJson(user)));
    } else {
      throw Exception('Failed to fetch user list');
    }
  }
}

I am not receiving any specific error message, but the user list does not display. I only see the message 'Failed to load user list' on the screen.

What I Have Tried:

class User {

  final int id;
  final String name;
  final String email;
  final String password;
  final int rol;
   
  const User({
    required this.id,
    required this.name,
    required this.email,
    required this.password,
    required this.rol,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'name': String name,
        'email': String email,
        'password': String password,
        'rol': int rol,
      } =>
        User(
          id: id,
          name: name,
          email: email,
          password: password,
          rol: rol,
        ),
      _ => throw const FormatException('Failed to load users'),
    };
  }
}

Upvotes: 1

Views: 63

Answers (1)

Zhentao
Zhentao

Reputation: 766

        } else if (snapshot.hasError) {
          return const Center(
            child: Text('Failed to load user list'),
          );
        }

because of this code, you can not find out the reason which cause this error, please use snapshot.error

        } else if (snapshot.hasError) {
          return const Center(
            child: Text('Error: ${snapshot.error}'),
          );
        }

Upvotes: 0

Related Questions