поменяла апишку

This commit is contained in:
Полина Чубыкина 2024-11-19 23:43:02 +04:00
parent 20171525ce
commit ca93e4ffc0
6 changed files with 84 additions and 140 deletions

View File

@ -4,16 +4,12 @@ part 'pokemon_dto.g.dart';
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class PokemonDto { class PokemonDto {
final List<PokemonDataDto>? results; final List<PokemonDataDto>? data;
final int? count; final MetaDto? meta;
final String? next;
final String? previous;
const PokemonDto({ const PokemonDto({
this.results, this.data,
this.count, this.meta,
this.next,
this.previous,
}); });
factory PokemonDto.fromJson(Map<String, dynamic> json) => _$PokemonDtoFromJson(json); factory PokemonDto.fromJson(Map<String, dynamic> json) => _$PokemonDtoFromJson(json);
@ -21,71 +17,48 @@ class PokemonDto {
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class PokemonDataDto { class PokemonDataDto {
final String? id;
final String? name; final String? name;
final String? url; final List<String>? types;
final String? imageUrl; final List<String>? evolvesTo;
final int? height; final PokemonImagesDto? images;
final int? weight;
final List<AbilityDto>? abilities;
// final PokemonAttributesDataDto? attributes;
const PokemonDataDto({ const PokemonDataDto({
this.id,
this.name, this.name,
this.url, this.types,
this.imageUrl, this.evolvesTo,
this.height, this.images,
this.weight,
this.abilities,
// this.attributes,
}); });
factory PokemonDataDto.fromJson(Map<String, dynamic> json) => _$PokemonDataDtoFromJson(json); factory PokemonDataDto.fromJson(Map<String, dynamic> json) => _$PokemonDataDtoFromJson(json);
} }
// @JsonSerializable(createToJson: false)
// class PokemonAttributesDataDto {
// final String? imageUrl;
// final int? height;
// final int? weight;
// final List<AbilityDto>? abilities;
// final PokemonSpritesDto? sprites;
//
// const PokemonAttributesDataDto({
// this.imageUrl,
// this.height,
// this.weight,
// this.abilities,
// this.sprites,
// });
//
// factory PokemonAttributesDataDto.fromJson(Map<String, dynamic> json) => _$PokemonAttributesDataDtoFromJson(json);
// }
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class AbilityDto { class PokemonImagesDto {
final AbilityDetailDto? ability; final String? small;
const AbilityDto({this.ability}); const PokemonImagesDto({this.small});
factory AbilityDto.fromJson(Map<String, dynamic> json) => _$AbilityDtoFromJson(json); factory PokemonImagesDto.fromJson(Map<String, dynamic> json) => _$PokemonImagesDtoFromJson(json);
} }
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class AbilityDetailDto { class MetaDto {
final String? name; final PaginationDto? pagination;
const AbilityDetailDto({this.name}); const MetaDto({this.pagination});
factory AbilityDetailDto.fromJson(Map<String, dynamic> json) => _$AbilityDetailDtoFromJson(json); factory MetaDto.fromJson(Map<String, dynamic> json) => _$MetaDtoFromJson(json);
} }
// @JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
// class PokemonSpritesDto { class PaginationDto {
// final String front_default; final int? current;
// final int? next;
// const PokemonSpritesDto({ final int? last;
// required this.front_default,
// }); const PaginationDto({this.current, this.next, this.last});
//
// factory PokemonSpritesDto.fromJson(Map<String, dynamic> json) => _$PokemonSpritesDtoFromJson(json); factory PaginationDto.fromJson(Map<String, dynamic> json) => _$PaginationDtoFromJson(json);
// } }

View File

@ -7,33 +7,42 @@ part of 'pokemon_dto.dart';
// ************************************************************************** // **************************************************************************
PokemonDto _$PokemonDtoFromJson(Map<String, dynamic> json) => PokemonDto( PokemonDto _$PokemonDtoFromJson(Map<String, dynamic> json) => PokemonDto(
results: (json['results'] as List<dynamic>?) data: (json['data'] as List<dynamic>?)
?.map((e) => PokemonDataDto.fromJson(e as Map<String, dynamic>)) ?.map((e) => PokemonDataDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
count: (json['count'] as num?)?.toInt(), meta: json['meta'] == null
next: json['next'] as String?, ? null
previous: json['previous'] as String?, : MetaDto.fromJson(json['meta'] as Map<String, dynamic>),
); );
PokemonDataDto _$PokemonDataDtoFromJson(Map<String, dynamic> json) => PokemonDataDto _$PokemonDataDtoFromJson(Map<String, dynamic> json) =>
PokemonDataDto( PokemonDataDto(
id: json['id'] as String?,
name: json['name'] as String?, name: json['name'] as String?,
url: json['url'] as String?, types:
imageUrl: json['imageUrl'] as String?, (json['types'] as List<dynamic>?)?.map((e) => e as String).toList(),
height: (json['height'] as num?)?.toInt(), evolvesTo: (json['evolvesTo'] as List<dynamic>?)
weight: (json['weight'] as num?)?.toInt(), ?.map((e) => e as String)
abilities: (json['abilities'] as List<dynamic>?)
?.map((e) => AbilityDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
); images: json['images'] == null
AbilityDto _$AbilityDtoFromJson(Map<String, dynamic> json) => AbilityDto(
ability: json['ability'] == null
? null ? null
: AbilityDetailDto.fromJson(json['ability'] as Map<String, dynamic>), : PokemonImagesDto.fromJson(json['images'] as Map<String, dynamic>),
); );
AbilityDetailDto _$AbilityDetailDtoFromJson(Map<String, dynamic> json) => PokemonImagesDto _$PokemonImagesDtoFromJson(Map<String, dynamic> json) =>
AbilityDetailDto( PokemonImagesDto(
name: json['name'] as String?, small: json['small'] as String?,
);
MetaDto _$MetaDtoFromJson(Map<String, dynamic> json) => MetaDto(
pagination: json['pagination'] == null
? null
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
);
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) =>
PaginationDto(
current: (json['current'] as num?)?.toInt(),
next: (json['next'] as num?)?.toInt(),
last: (json['last'] as num?)?.toInt(),
); );

View File

@ -1,24 +1,29 @@
import 'package:mobilki_lab1/data/dtos/pokemon_dto.dart'; import 'package:mobilki_lab1/data/dtos/pokemon_dto.dart';
import 'package:mobilki_lab1/domain/models/card.dart'; import 'package:mobilki_lab1/domain/models/card.dart';
import 'package:mobilki_lab1/domain/models/home.dart'; import 'package:mobilki_lab1/domain/models/home.dart';
import 'package:flutter/material.dart';
const _imagePlaceholder = const _imagePlaceholder =
'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png'; 'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png';
extension PokemonDtoToModel on PokemonDto { extension PokemonDtoToModel on PokemonDto {
HomeData toDomain() => HomeData( HomeData toDomain() => HomeData(
data: results?.map((e) => e.toDomain()).toList(), data: data?.map((e) => e.toDomain()).toList(),
nextPage: next != null ? int.tryParse(next!.split('=')[1].split('&')[0]) : null, nextPage: meta?.pagination?.next,
); );
} }
extension PokemonDataDtoToModel on PokemonDataDto { extension PokemonDataDtoToModel on PokemonDataDto {
CardData toDomain() => CardData( CardData toDomain() => CardData(
name ?? 'UNKNOWN', name ?? 'UNKNOWN',
imageUrl: imageUrl ?? _imagePlaceholder, imageUrl: images?.small ?? _imagePlaceholder,
descriptionText: 'Height: ${height ?? 'UNKNOWN'} cm, Weight: ${weight ?? 'UNKNOWN'} g, Abilities: ${abilities?.map((ability) => ability.ability?.name ?? 'UNKNOWN').join(', ') ?? 'UNKNOWN'}', descriptionText: _makeDescriptionText(types, evolvesTo),
// imageUrl: attributes?.sprites?.front_default ?? _imagePlaceholder, id: id,
// descriptionText: 'Height: ${attributes?.height ?? 'UNKNOWN'} cm, Weight: ${attributes?.weight ?? 'UNKNOWN'} g, Abilities: ${attributes?.abilities?.map((ability) => ability.ability?.name ?? 'UNKNOWN').join(', ') ?? 'UNKNOWN'}',
id: url?.split('/')[6] ?? 'UNKNOWN',
); );
String _makeDescriptionText(List<String>? types, List<String>? evolvesTo) {
final typeText = types != null && types.isNotEmpty ? 'Types: ${types.join(", ")}' : '';
final evolvesToText = evolvesTo != null && evolvesTo.isNotEmpty ? 'Evolves To: ${evolvesTo.join(", ")}' : '';
return '$typeText\n$evolvesToText'.trim();
}
} }

View File

@ -5,79 +5,36 @@ import 'package:mobilki_lab1/data/repositories/api_interface.dart';
import 'package:mobilki_lab1/domain/models/home.dart'; import 'package:mobilki_lab1/domain/models/home.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart'; import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class PokeRepository extends ApiInterface { class PokemonRepository extends ApiInterface {
static final Dio _dio = Dio() static final Dio _dio = Dio()
..interceptors.add(PrettyDioLogger( ..interceptors.add(PrettyDioLogger(
requestHeader: true, requestHeader: true,
requestBody: true, requestBody: true,
)); ));
static const String _baseUrl = 'https://pokeapi.co/api/v2'; static const String _baseUrl = 'https://api.pokemontcg.io/v2';
@override @override
Future<HomeData?> loadData({ Future<HomeData?> loadData({
OnErrorCallback? onError, OnErrorCallback? onError,
String? q, String? q,
int page = 0, int page = 1,
int pageSize = 5, int pageSize = 10,
}) async { }) async {
try { try {
String url = '$_baseUrl/pokemon'; final String url = '$_baseUrl/cards';
Map<String, dynamic> queryParameters = {
'offset': page,
'limit': pageSize,
};
// if (q != null && q.isNotEmpty) {
// url = '$_baseUrl/pokemon/$q';
// queryParameters = {
// 'offset': page,
// 'limit': pageSize,
// };
// }
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>( final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
url, url,
queryParameters: queryParameters, queryParameters: {
'q': q,
'page': page,
'pageSize': pageSize,
},
); );
// final PokemonDto dto = PokemonDto.fromJson(response.data as Map<String, dynamic>);
// final HomeData data = dto.toDomain();
final PokemonDto dto = PokemonDto.fromJson(response.data as Map<String, dynamic>); final PokemonDto dto = PokemonDto.fromJson(response.data as Map<String, dynamic>);
final List<PokemonDataDto> pokemonDataList = dto.results ?? []; final HomeData data = dto.toDomain();
final List<PokemonDataDto> updatedPokemonDataList = await Future.wait(pokemonDataList.map((pokemonData) async {
final id = pokemonData.url?.split('/')[6];
final detailsUrl = 'https://pokeapi.co/api/v2/pokemon/$id';
final detailsResponse = await _dio.get<Map<dynamic, dynamic>>(detailsUrl);
final int height = detailsResponse.data?['height'];
final int weight = detailsResponse.data?['weight'];
final List<dynamic> abilities = detailsResponse.data?['abilities'];
final List<AbilityDto> abilityDtos = abilities.map((ability) {
return AbilityDto(
ability: AbilityDetailDto(
name: ability['ability']['name'],
),
);
}).toList();
return PokemonDataDto(
name: pokemonData.name,
url: pokemonData.url,
imageUrl: 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/$id.png',
height: height,
weight: weight,
abilities: abilityDtos,
);
}));
final HomeData data = HomeData(
data: updatedPokemonDataList.map((e) => e.toDomain()).toList(),
nextPage: dto.next != null ? int.tryParse(dto.next!.split('=')[1].split('&')[0]) : null,
);
return data; return data;
} on DioException catch (e) { } on DioException catch (e) {
onError?.call(e.error?.toString()); onError?.call(e.error?.toString());

View File

@ -35,15 +35,15 @@ class MyApp extends StatelessWidget {
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true, useMaterial3: true,
), ),
home: RepositoryProvider<PokeRepository>( home: RepositoryProvider<PokemonRepository>(
lazy: true, lazy: true,
create: (_) => PokeRepository(), create: (_) => PokemonRepository(),
child: BlocProvider<LikeBloc>( child: BlocProvider<LikeBloc>(
lazy: false, lazy: false,
create: (context) => LikeBloc(), create: (context) => LikeBloc(),
child: BlocProvider<HomeBloc>( child: BlocProvider<HomeBloc>(
lazy: false, lazy: false,
create: (context) => HomeBloc(context.read<PokeRepository>()), create: (context) => HomeBloc(context.read<PokemonRepository>()),
child: const MyHomePage(title: 'Чубыкина Полина Павловна'), child: const MyHomePage(title: 'Чубыкина Полина Павловна'),
), ),
), ),

View File

@ -4,7 +4,7 @@ import 'package:mobilki_lab1/presentation/home_page/bloc/events.dart';
import 'package:mobilki_lab1/presentation/home_page/bloc/state.dart'; import 'package:mobilki_lab1/presentation/home_page/bloc/state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> { class HomeBloc extends Bloc<HomeEvent, HomeState> {
final PokeRepository repo; final PokemonRepository repo;
HomeBloc(this.repo) : super(const HomeState()) { HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData); on<HomeLoadDataEvent>(_onLoadData);