Home > OS >  Fetch data user with DIO API
Fetch data user with DIO API

Time:09-01

I've been learning for days about him. But I still can't display it on screen. Maybe anyone can help ? please check it. i want to get some user data on my screen with Dio Package

in this dio client i try tu generalize every request in 1 .dart

Dio_Client.dart

import 'package:dio/dio.dart';
import 'package:latihan_dio/dio_interceptor.dart';

import '../../../../dio_client.dart';
import '/src/features/home/domain/user.dart';

enum RequestType { GET, POST, PUT, PATCH, DELETE }

class DioClient {
  final dio = createDio();

  DioClient._internal();

  static final _singleton = DioClient._internal();

  factory DioClient() => _singleton;

  static Dio createDio() {
    var dio = Dio(BaseOptions(
      baseUrl: "https://reqres.in/api/users?page=2",
      receiveTimeout: 20000, // 20 seconds
      connectTimeout: 20000,
      sendTimeout: 20000,
    ));

    // dio.interceptors.addAll({
    //   AuthInterceptor(dio),
    // });
    // dio.interceptors.addAll({
    //   Logging(dio),
    // });

    return dio;
  }

  Future<Response<dynamic>> apiCall({
    required String url,
    required RequestType requestType,
    Map<String, dynamic>? queryParameters,
    Map<String, dynamic>? body,
    Map<String, String>? header,
    RequestOptions? requestOptions,
  }) async {
    late Response result;
    // try {
    switch (requestType) {
      case RequestType.GET:
        {
          Options options = Options(headers: header);
          result = await dio.get(url,
              queryParameters: queryParameters, options: options);
          break;
        }
      case RequestType.POST:
        {
          Options options = Options(headers: header);
          result = await dio.post(url, data: body, options: options);
          break;
        }
      case RequestType.DELETE:
        {
          Options options = Options(headers: header);
          result =
              await dio.delete(url, data: queryParameters, options: options);
          break;
        }
      case RequestType.PUT:
        {
          Options options = Options(headers: header);
          result = await dio.put(url, data: body, options: options);
          break;
        }
      case RequestType.PATCH:
        {
          Options options = Options(headers: header);
          result = await dio.patch(url, data: body, options: options);
          break;
        }
    }
    return result;
    //   if(result != null) {
    // //     return NetworkResponse.success(result.data);
    // //   } else {
    // //     return const NetworkResponse.error("Data is null");
    // //   }
    // // }on DioError catch (error) {
    // //   return NetworkResponse.error(error.message);
    // // } catch (error) {
    // //   return NetworkResponse.error(error.toString());
  }
}


// }**

in this home screen i try to call api wit fetch user home_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:latihan_dio/src/features/home/domain/user.dart';

import '../../../../dio_client.dart';

class myHomepage extends StatefulWidget {
  const myHomepage({Key? key}) : super(key: key);

  @override
  State<myHomepage> createState() => _myHomepageState();
}

class _myHomepageState extends State<myHomepage> {
  List<User> users = [];
  var selectedIndex = 0;
  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
            child: Column(
              children: [
                ListView.builder(
                  // padding: EdgeInsets.symmetric(vertical: 16.5),
                  // scrollDirection: Axis.horizontal,
                  itemCount: users.length,
                  
                  itemBuilder: (context, index) {
                    return Center(
                      child: Center(
                          child: Text( 
                        '[data]${users[index]}',
                        style: TextStyle(
                          fontSize: 100,
                          color: Colors.red,
                        ),
                      )),
                    );
                  },
                ),
                // Text('data2'),
                // Text('data3'),
                // Text('data4'),
              ],
            ),
          ),
          TextButton(
            onPressed: () {},
            child: Text(
              'GET',
              style: TextStyle(
                fontSize: 100,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Future<void> fetchData() async {
  var Response = await DioClient().apiCall(
    url: 'https://reqres.in/api/users?page=2',
    requestType: RequestType.GET,
    // queryParameters: {},
  );

  List<dynamic> listUser = Response.data['result'];
  List<User> users = listUser.map((e) => User.fromJson(e)).toList();
}

user.dart iam using freezed package for models,

// To parse this JSON data, do
//
//     final user = userFromMap(jsonString);

import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';

part 'user.freezed.dart';
part 'user.g.dart';

@freezed
abstract class User with _$User {
  const factory User({
    @JsonKey(name: 'id') int? id,
    @JsonKey(name: 'email') String? email,
    @JsonKey(name: 'first_name') String? firstName,
    @JsonKey(name: 'last_name') String? lastName,
    @JsonKey(name: 'avatar') String? avatar,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

CodePudding user response:

Instead of call async in initState, use FutureBuilder and you not checking the response to be success and also your get your list by calling Response.data['result'] instead of Response.data['data'] .Do like this:

Future<List<User?>> fetchData() async {
    var Response = await DioClient().apiCall(
      url: 'https://reqres.in/api/users?page=2',
      requestType: RequestType.GET,
      // queryParameters: {},
    );
    if (Response.statusCode == 200) {
      List<dynamic> listUser = Response.data['data'];
      List<User> users = listUser.map((e) => User.fromJson(e)).toList();
      return users;
    } else {
      return [];
    }
  }

then use it like this:

Center(
        child: FutureBuilder<List<User?>>(
          future: fetchData(),
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
                return Text('Loading....');
              default:
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  List<User?> data = snapshot.data ?? [];

                  return ListView.builder(
                    itemBuilder: (context, index) {
                      return Column(children: [
                        Text(data[index]?.firstName?? ''),
                      ]);
                    },
                    itemCount: data.length,
                  );
                }
            }
          },
        ),
      )

enter image description here

CodePudding user response:

try this

Future<void> fetchData() async {
  var Response = await DioClient().apiCall(
    url: 'https://reqres.in/api/users?page=2',
    requestType: RequestType.GET,
    // queryParameters: {},
  );

  List<dynamic> listUser = Response.data['result'];
  users = listUser.map((e) => User.fromJson(e)).toList();
}

//remove reinit of userslist

CodePudding user response:

Future<void> fetchData() async {
  var Response = await DioClient().apiCall(
    url: 'https://reqres.in/api/users?page=2',
    requestType: RequestType.GET,
    // queryParameters: {},
  );

  List<dynamic> listUser = Response.data;

   // OR

  List<dynamic> listUser = Response.data['data]; // if you want to acces s data inside it

  List<User> users = listUser.map((e) => User.fromJson(e)).toList();
}

Try this

  • Related