skip to Main Content

I tried to show data by using reqres API: https://reqres.in/api/users?page=2 in my flutter app but it doesn’t show any single data in here, i make user.response.dart by copying Get List User reqres response and convert it to Json to Dart

user_response.dart

class UserResponse {
  int? page;
  int? perPage;
  int? total;
  int? totalPages;
  List<Data>? data;
  Support? support;

  UserResponse(
      {this.page,
      this.perPage,
      this.total,
      this.totalPages,
      this.data,
      this.support});

  UserResponse.fromJson(Map<String, dynamic> json) {
    page = json['page'];
    perPage = json['per_page'];
    total = json['total'];
    totalPages = json['total_pages'];
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((v) {
        data!.add(new Data.fromJson(v));
      });
    }
    support =
        json['support'] != null ? new Support.fromJson(json['support']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['page'] = this.page;
    data['per_page'] = this.perPage;
    data['total'] = this.total;
    data['total_pages'] = this.totalPages;
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    if (this.support != null) {
      data['support'] = this.support!.toJson();
    }
    return data;
  }
}

class Data {
  int? id;
  String? email;
  String? firstName;
  String? lastName;
  String? avatar;

  Data({this.id, this.email, this.firstName, this.lastName, this.avatar});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    firstName = json['first_name'];
    lastName = json['last_name'];
    avatar = json['avatar'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['email'] = this.email;
    data['first_name'] = this.firstName;
    data['last_name'] = this.lastName;
    data['avatar'] = this.avatar;
    return data;
  }
}

class Support {
  String? url;
  String? text;

  Support({this.url, this.text});

  Support.fromJson(Map<String, dynamic> json) {
    url = json['url'];
    text = json['text'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['url'] = this.url;
    data['text'] = this.text;
    return data;
  }
}

profile_repository.dart

import 'package:autoduck_state2/domain/auth/model/login_request.dart';
import 'package:autoduck_state2/domain/auth/model/login_response.dart';
import 'package:autoduck_state2/domain/core/user/model/user_response.dart';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';

class ProfileRepository {
  Dio _dio = Dio();

  //Either digunakan untuk mengembalikan data left atau right,
  //Jika data salah maka akan mengembalikan String,Jika data benar maka akan mengembalikan UserResponse
  Future<Either<String, UserResponse>> getAllUserData(
      {required LoginRequest loginRequest}) async {
    Response _response;

    try {
      _response = await _dio.get("https://reqres.in/api/users?page=2",
          data: loginRequest.toJson());
      //Jadi pada awal kita minta string, pada akhir dikasi string
      UserResponse _userResponse = UserResponse.fromJson(_response.data);
      return right(_userResponse);
    } on DioException catch (e) {
      //error yang dihasilkan oleh dio
      print(
          "DioException: ${e.response?.statusCode}, ${e.response?.statusMessage}");
      String errorMessage = e.response!.data.toString();

      // if(e.type == DioExceptionType.badResponse) {

      // }
      switch (e.type) {
        case DioExceptionType.connectionTimeout:
          // TODO: Handle this case.
          break;
        case DioExceptionType.sendTimeout:
          // TODO: Handle this case.
          break;
        case DioExceptionType.receiveTimeout:
          // TODO: Handle this case.
          break;
        case DioExceptionType.badCertificate:
          // TODO: Handle this case.
          break;
        case DioExceptionType.badResponse:
          errorMessage = e.response!.data['error'];
          break;
        case DioExceptionType.cancel:
          // TODO: Handle this case.
          break;
        case DioExceptionType.connectionError:
          // TODO: Handle this case.
          break;
        case DioExceptionType.unknown:
          // TODO: Handle this case.
          break;
      }
      return left(errorMessage);
    }
  }
}

home_page.dart

import 'package:autoduck_state2/application/profile/bloc/profileb_bloc.dart';
import 'package:autoduck_state2/domain/auth/model/login_response.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key, required this.loginResponse}) : super(key: key);

  final LoginResponse loginResponse;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => ProfilebBloc()..add(ProfilebEvent.getAllUserData()),
      child: BlocConsumer<ProfilebBloc, ProfilebState>(
        listener: (context, state) {
          //maybeMap untuk mengambil sedikit data
          state.maybeMap(
            orElse: () {},
            isLoading: (value) {
              print("Is loading");
            },
            isSuccess: (value) {
              print(value.userResponse.toJson());
            },
          );
        },
        builder: (context, state) {
          return state.maybeMap(
            orElse: () => homePageError(),
            isLoading: (e) => homePageLoading(),
            isSuccess: (value) => homePageScaffold(),
            isError: (value) => homePageError(),
          );
        },
      ),
    );
  }

  Scaffold homePageError() {
    return Scaffold(
      body: Column(
        children: [
          Text("Something error"),
          Text("Something error"),
          Text("Something error"),
          Text("Something error"),
          IconButton(onPressed: () {}, icon: Icon(Icons.replay)),
        ],
      ),
    );
  }

  Scaffold homePageLoading() => Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );

  Scaffold homePageScaffold() {
    return Scaffold(
      appBar: AppBar(title: Text(widget.loginResponse.token ?? "No Token")),
      body: Container(
        child: ListView.builder(
            itemBuilder: (context, index) => ListTile(
                  title: Text("nama"),
                )),
      ),
    );
  }
}

I’m expecting to fix my code quickly like atleast 12 hours after asking this

2

Answers


  1. have you checked if your server has a valid SSL certificate, if your not sure, first add httpOverrides to your main and check if the request works, if it works then the problem is your server certificate

    import 'dart:io';
    
    
        class MyHttpOverrides extends HttpOverrides {
        
          @override
          HttpClient createHttpClient(SecurityContext? context) {
            return super.createHttpClient(context)
              ..badCertificateCallback =
                  (X509Certificate cert, String host, int port) => true;
          }
        }
        
        Future<void> main() async {
          HttpOverrides.global = MyHttpOverrides();
          WidgetsFlutterBinding.ensureInitialized();
        }
    
    Login or Signup to reply.
  2. I guess what your looking for is this

    import 'package:dio/dio.dart';
    import 'package:flutter/material.dart';
    import 'dart:convert' as convert;
    
    void main() {
      runApp(const MyApp());
    }
    
    class UserResponse {
      int? page;
      int? perPage;
      int? total;
      int? totalPages;
      List<Data>? data;
      Support? support;
    
      UserResponse(
          {this.page,
          this.perPage,
          this.total,
          this.totalPages,
          this.data,
          this.support});
    
      UserResponse.fromJson(Map<String, dynamic> json) {
        page = json['page'];
        perPage = json['per_page'];
        total = json['total'];
        totalPages = json['total_pages'];
        if (json['data'] != null) {
          data = <Data>[];
          json['data'].forEach((v) {
            data!.add(new Data.fromJson(v));
          });
        }
        support =
            json['support'] != null ? new Support.fromJson(json['support']) : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['page'] = this.page;
        data['per_page'] = this.perPage;
        data['total'] = this.total;
        data['total_pages'] = this.totalPages;
        if (this.data != null) {
          data['data'] = this.data!.map((v) => v.toJson()).toList();
        }
        if (this.support != null) {
          data['support'] = this.support!.toJson();
        }
        return data;
      }
    }
    
    class Data {
      int? id;
      String? email;
      String? firstName;
      String? lastName;
      String? avatar;
    
      Data({this.id, this.email, this.firstName, this.lastName, this.avatar});
    
      Data.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        email = json['email'];
        firstName = json['first_name'];
        lastName = json['last_name'];
        avatar = json['avatar'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['email'] = this.email;
        data['first_name'] = this.firstName;
        data['last_name'] = this.lastName;
        data['avatar'] = this.avatar;
        return data;
      }
    }
    
    class Support {
      String? url;
      String? text;
    
      Support({this.url, this.text});
    
      Support.fromJson(Map<String, dynamic> json) {
        url = json['url'];
        text = json['text'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['url'] = this.url;
        data['text'] = this.text;
        return data;
      }
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      late Future<UserResponse?> usersFuture;
      @override
      void initState() {
        usersFuture = getAllUsers();
        super.initState();
      }
    
      var dio = Dio();
      Future<UserResponse?> getAllUsers() async {
        var response = await dio.request(
          'https://reqres.in/api/users?page=2',
          options: Options(
            method: 'GET',
          ),
        );
    
        if (response.statusCode == 200) {
          UserResponse _userResponse = UserResponse.fromJson(response.data);
          return _userResponse;
        } else {
          return null;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: FutureBuilder(
            future: usersFuture,
            builder: (ctx, snapshot) {
              // Displaying LoadingSpinner to indicate waiting state
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Center(
                        child: CircularProgressIndicator(),
                      )
                    ]);
              } else if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text(snapshot.error.toString());
                } else {
                  // PagingMovieModel? wfmovies = snapshot.data;
                  UserResponse? users = snapshot.data;
                  ///////////////////
    
                  return users == null
                      ? const Column(
                          children: [
                            Center(
                              child: Text(
                                  "Failed to get data from server, please check your internet connection"),
                            ),
                          ],
                        )
                      : ListView(
                          children: List.generate(
                            users.data!.length,
                            (index) {
                              Data user = users.data![index];
                              return ListTile(
                                  leading: CircleAvatar(
                                    child: Image.network(user.avatar ??
                                        "https://fakeimg.pl/200x200"),
                                  ),
                                  title: Text("${user.firstName} ${user.lastName}"),
                                  subtitle: Text(user.email ?? ""));
                            },
                          ),
                        );
                }
              } else {
                return const Text(
                  "Something went wrong, please try again laiter",
                  style: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 16.0,
                    color: Colors.white,
                  ),
                );
              }
            },
          ),
        );
      }
    }
    

    The result must look like this
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search