почти слэй но пагинация не работает

This commit is contained in:
Полина Чубыкина 2024-11-20 00:12:00 +04:00
parent 89b3891506
commit 9c16de318d
7 changed files with 121 additions and 90 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,46 +17,61 @@ 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 List<String>? evolvesTo;
final List<PokemonAbilityDto>? abilities;
final PokemonImagesDto? images;
const PokemonDataDto({ const PokemonDataDto({
this.id,
this.name, this.name,
this.url, this.types,
this.evolvesTo,
this.abilities,
this.images,
}); });
factory PokemonDataDto.fromJson(Map<String, dynamic> json) => _$PokemonDataDtoFromJson(json); factory PokemonDataDto.fromJson(Map<String, dynamic> json) => _$PokemonDataDtoFromJson(json);
} }
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class PokemonDetailsDto { class PokemonAbilityDto {
final int? height;
final int? weight;
final List<AbilityDto>? abilities;
const PokemonDetailsDto({
this.height,
this.weight,
this.abilities,
});
factory PokemonDetailsDto.fromJson(Map<String, dynamic> json) => _$PokemonDetailsDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class AbilityDto {
final AbilityDetailDto? ability;
const AbilityDto({this.ability});
factory AbilityDto.fromJson(Map<String, dynamic> json) => _$AbilityDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class AbilityDetailDto {
final String? name; final String? name;
final String? text;
final String? type;
const AbilityDetailDto({this.name}); const PokemonAbilityDto({this.name, this.text, this.type});
factory AbilityDetailDto.fromJson(Map<String, dynamic> json) => _$AbilityDetailDtoFromJson(json); factory PokemonAbilityDto.fromJson(Map<String, dynamic> json) => _$PokemonAbilityDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PokemonImagesDto {
final String? large;
const PokemonImagesDto({this.large});
factory PokemonImagesDto.fromJson(Map<String, dynamic> json) => _$PokemonImagesDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class MetaDto {
final PaginationDto? pagination;
const MetaDto({this.pagination});
factory MetaDto.fromJson(Map<String, dynamic> json) => _$MetaDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PaginationDto {
final int? current;
final int? next;
final int? last;
const PaginationDto({this.current, this.next, this.last});
factory PaginationDto.fromJson(Map<String, dynamic> json) => _$PaginationDtoFromJson(json);
} }

View File

@ -7,36 +7,52 @@ 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:
); (json['types'] as List<dynamic>?)?.map((e) => e as String).toList(),
evolvesTo: (json['evolvesTo'] as List<dynamic>?)
PokemonDetailsDto _$PokemonDetailsDtoFromJson(Map<String, dynamic> json) => ?.map((e) => e as String)
PokemonDetailsDto(
height: (json['height'] as num?)?.toInt(),
weight: (json['weight'] as num?)?.toInt(),
abilities: (json['abilities'] as List<dynamic>?)
?.map((e) => AbilityDto.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
); abilities: (json['abilities'] as List<dynamic>?)
?.map((e) => PokemonAbilityDto.fromJson(e as Map<String, dynamic>))
AbilityDto _$AbilityDtoFromJson(Map<String, dynamic> json) => AbilityDto( .toList(),
ability: json['ability'] == null images: json['images'] == 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) => PokemonAbilityDto _$PokemonAbilityDtoFromJson(Map<String, dynamic> json) =>
AbilityDetailDto( PokemonAbilityDto(
name: json['name'] as String?, name: json['name'] as String?,
text: json['text'] as String?,
type: json['type'] as String?,
);
PokemonImagesDto _$PokemonImagesDtoFromJson(Map<String, dynamic> json) =>
PokemonImagesDto(
large: json['large'] 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,34 +1,39 @@
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 toDomain() => CardData(
final id = url?.split('/')[6] ?? 'UNKNOWN';
final imageUrl = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/$id.png';
return CardData(
name ?? 'UNKNOWN', name ?? 'UNKNOWN',
imageUrl: imageUrl, imageUrl: images?.large ?? _imagePlaceholder,
descriptionText: 'ID: $id', descriptionText: _makeDescriptionText(types, evolvesTo, abilities),
id: id, id: id,
); );
}
}
extension PokemonDetailsDtoToModel on PokemonDetailsDto { String _makeDescriptionText(
String toDescriptionText() { List<String>? types,
final abilitiesText = abilities?.map((ability) => ability.ability?.name ?? 'UNKNOWN').join(', ') ?? 'UNKNOWN'; List<String>? evolvesTo,
return 'Height: ${height ?? 'UNKNOWN'} cm, Weight: ${weight ?? 'UNKNOWN'} kg, Abilities: $abilitiesText'; List<PokemonAbilityDto>? abilities,
) {
final typeText = types != null && types.isNotEmpty ? 'Types: ${types.join(", ")}' : '';
final evolvesToText = evolvesTo != null && evolvesTo.isNotEmpty ? 'Evolves To: ${evolvesTo.join(", ")}' : '';
final abilitiesText = abilities != null && abilities.isNotEmpty ? 'Abilities: ${abilities.map((a) => a.name).join(", ")}' : '';
return [
typeText,
evolvesToText,
abilitiesText,
].where((text) => text.isNotEmpty).join('\n');
} }
} }

View File

@ -5,33 +5,32 @@ 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 = 1, int page = 1,
int pageSize = 25, int pageSize = 10,
}) async { }) async {
try { try {
final String url = '$_baseUrl/pokemon'; final String url = '$_baseUrl/cards';
final Map<String, dynamic> queryParameters = { final Map<String, dynamic> queryParameters = {
'offset': (page - 1) * pageSize, 'page': page,
'limit': pageSize, 'pageSize': pageSize,
}; };
// Если есть поисковый запрос, добавляем его в параметры запроса if (q != null) {
if (q != null && q.isNotEmpty) { queryParameters['q'] = 'name:$q*';
queryParameters['name'] = q;
} }
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>( final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(

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<PotterRepository>( home: RepositoryProvider<PokemonRepository>(
lazy: true, lazy: true,
create: (_) => PotterRepository(), 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<PotterRepository>()), create: (context) => HomeBloc(context.read<PokemonRepository>()),
child: const MyHomePage(title: 'Чубыкина Полина Павловна'), child: const MyHomePage(title: 'Чубыкина Полина Павловна'),
), ),
), ),

View File

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

View File

@ -63,7 +63,7 @@ class BodyState extends State<Body> {
} }
void _onNextPageListener() { void _onNextPageListener() {
if (scrollController.offset > scrollController.position.maxScrollExtent) { if (scrollController.offset >= scrollController.position.maxScrollExtent) {
final bloc = context.read<HomeBloc>(); final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading) { if (!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent( bloc.add(HomeLoadDataEvent(