dart 无法从Flutter应用程序中的API检索数据

svgewumm  于 2023-09-28  发布在  Flutter
关注(0)|答案(2)|浏览(120)

我尝试使用reqres API显示数据:https://reqres.in/api/users?page=2在我的Flutter应用程序,但它不显示任何单一的数据在这里,我使用户.响应.dart通过复制获取列表用户reqres响应,并将其转换为JSON到 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"),
                )),
      ),
    );
  }
}

我希望在问完这个问题后至少12个小时能快速修复我的代码

wwwo4jvm

wwwo4jvm1#

你有没有检查过你的服务器是否有有效的SSL证书,如果你不确定,首先将httpOverrides添加到你的主服务器,并检查请求是否有效,如果有效,那么问题出在你的服务器证书上

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();
    }
rkttyhzu

rkttyhzu2#

我猜你要找的是这个

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

如果你想添加新的用户数据,在将来的情况下处理分页,你必须这样做

UserResponse? userresponse = await getAllUsers(newpageno);
    if(userresponse != null){
    List<Data> newusers = userresponse.data;
     usersFuture.then((value) => value!..results.addAll(newusers));
    }

结果一定是这样的

相关问题