поломала пагинацию

This commit is contained in:
Полина Чубыкина 2024-11-16 13:37:18 +04:00
parent 98c063ed2f
commit 97cbcba226
9 changed files with 199 additions and 77 deletions

View File

@ -82,8 +82,7 @@ abstract class AppLocale {
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates =
<LocalizationsDelegate<dynamic>>[
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
@ -91,7 +90,10 @@ abstract class AppLocale {
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[Locale('en'), Locale('ru')];
static const List<Locale> supportedLocales = <Locale>[
Locale('en'),
Locale('ru')
];
/// No description provided for @search.
///
@ -134,17 +136,18 @@ class _AppLocaleDelegate extends LocalizationsDelegate<AppLocale> {
}
AppLocale lookupAppLocale(Locale locale) {
// Lookup logic when only language code is specified.
switch (locale.languageCode) {
case 'en':
return AppLocaleEn();
case 'ru':
return AppLocaleRu();
case 'en': return AppLocaleEn();
case 'ru': return AppLocaleRu();
}
throw FlutterError(
'AppLocale.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.');
'AppLocale.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.'
);
}

View File

@ -6,22 +6,28 @@ part of 'characters_dto.dart';
// JsonSerializableGenerator
// **************************************************************************
CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) => CharactersDto(
CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) =>
CharactersDto(
data: (json['data'] as List<dynamic>?)
?.map((e) => CharacterDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
meta: json['meta'] == null ? null : MetaDto.fromJson(json['meta'] as Map<String, dynamic>),
meta: json['meta'] == null
? null
: MetaDto.fromJson(json['meta'] as Map<String, dynamic>),
);
CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) => CharacterDataDto(
CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) =>
CharacterDataDto(
id: json['id'] as String?,
type: json['type'] as String?,
attributes: json['attributes'] == null
? null
: CharacterAttributesDataDto.fromJson(json['attributes'] as Map<String, dynamic>),
: CharacterAttributesDataDto.fromJson(
json['attributes'] as Map<String, dynamic>),
);
CharacterAttributesDataDto _$CharacterAttributesDataDtoFromJson(Map<String, dynamic> json) =>
CharacterAttributesDataDto _$CharacterAttributesDataDtoFromJson(
Map<String, dynamic> json) =>
CharacterAttributesDataDto(
name: json['name'] as String?,
born: json['born'] as String?,
@ -35,7 +41,8 @@ MetaDto _$MetaDtoFromJson(Map<String, dynamic> json) => MetaDto(
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
);
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) => PaginationDto(
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

@ -4,56 +4,63 @@ part 'pokemon_dto.g.dart';
@JsonSerializable(createToJson: false)
class PokemonDto {
final int id;
final String name;
final List<PokemonTypeDto> types;
final PokemonSpritesDto sprites;
final List<PokemonDataDto>? results;
final int? count;
final String? next;
final String? previous;
const PokemonDto({
required this.id,
required this.name,
required this.types,
required this.sprites,
this.results,
this.count,
this.next,
this.previous,
});
factory PokemonDto.fromJson(Map<String, dynamic> json) => _$PokemonDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PokemonTypeDto {
final int slot;
final PokemonTypeDetailDto type;
class PokemonDataDto {
final String? name;
final String? url;
const PokemonTypeDto({
required this.slot,
required this.type,
const PokemonDataDto({
this.name,
this.url,
});
factory PokemonTypeDto.fromJson(Map<String, dynamic> json) => _$PokemonTypeDtoFromJson(json);
factory PokemonDataDto.fromJson(Map<String, dynamic> json) => _$PokemonDataDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PokemonTypeDetailDto {
final String name;
final String url;
class PokemonDetailsDto {
final int? height;
final int? weight;
final List<AbilityDto>? abilities;
const PokemonTypeDetailDto({
required this.name,
required this.url,
const PokemonDetailsDto({
this.height,
this.weight,
this.abilities,
});
factory PokemonTypeDetailDto.fromJson(Map<String, dynamic> json) =>
_$PokemonTypeDetailDtoFromJson(json);
factory PokemonDetailsDto.fromJson(Map<String, dynamic> json) => _$PokemonDetailsDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class PokemonSpritesDto {
final String front_default;
class AbilityDto {
final AbilityDetailDto? ability;
const PokemonSpritesDto({
required this.front_default,
});
const AbilityDto({this.ability});
factory PokemonSpritesDto.fromJson(Map<String, dynamic> json) =>
_$PokemonSpritesDtoFromJson(json);
factory AbilityDto.fromJson(Map<String, dynamic> json) => _$AbilityDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class AbilityDetailDto {
final String? name;
const AbilityDetailDto({this.name});
factory AbilityDetailDto.fromJson(Map<String, dynamic> json) => _$AbilityDetailDtoFromJson(json);
}

View File

@ -7,25 +7,36 @@ part of 'pokemon_dto.dart';
// **************************************************************************
PokemonDto _$PokemonDtoFromJson(Map<String, dynamic> json) => PokemonDto(
id: (json['id'] as num).toInt(),
name: json['name'] as String,
types: (json['types'] as List<dynamic>)
.map((e) => PokemonTypeDto.fromJson(e as Map<String, dynamic>))
results: (json['results'] as List<dynamic>?)
?.map((e) => PokemonDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
sprites: PokemonSpritesDto.fromJson(json['sprites'] as Map<String, dynamic>),
count: (json['count'] as num?)?.toInt(),
next: json['next'] as String?,
previous: json['previous'] as String?,
);
PokemonTypeDto _$PokemonTypeDtoFromJson(Map<String, dynamic> json) => PokemonTypeDto(
slot: (json['slot'] as num).toInt(),
type: PokemonTypeDetailDto.fromJson(json['type'] as Map<String, dynamic>),
PokemonDataDto _$PokemonDataDtoFromJson(Map<String, dynamic> json) =>
PokemonDataDto(
name: json['name'] as String?,
url: json['url'] as String?,
);
PokemonTypeDetailDto _$PokemonTypeDetailDtoFromJson(Map<String, dynamic> json) =>
PokemonTypeDetailDto(
name: json['name'] as String,
url: json['url'] as String,
PokemonDetailsDto _$PokemonDetailsDtoFromJson(Map<String, dynamic> json) =>
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(),
);
PokemonSpritesDto _$PokemonSpritesDtoFromJson(Map<String, dynamic> json) => PokemonSpritesDto(
front_default: json['front_default'] as String,
AbilityDto _$AbilityDtoFromJson(Map<String, dynamic> json) => AbilityDto(
ability: json['ability'] == null
? null
: AbilityDetailDto.fromJson(json['ability'] as Map<String, dynamic>),
);
AbilityDetailDto _$AbilityDetailDtoFromJson(Map<String, dynamic> json) =>
AbilityDetailDto(
name: json['name'] as String?,
);

View File

@ -1,17 +1,34 @@
import 'package:mobilki_lab1/data/dtos/pokemon_dto.dart';
import 'package:mobilki_lab1/domain/models/card.dart';
import 'package:mobilki_lab1/domain/models/home.dart';
const _imagePlaceholder =
'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png';
extension PokemonDtoToModel on PokemonDto {
CardData toDomain() => CardData(
name,
imageUrl: sprites.front_default ?? _imagePlaceholder,
descriptionText: _makeDescriptionText(types),
);
HomeData toDomain() => HomeData(
data: results?.map((e) => e.toDomain()).toList(),
nextPage: next != null ? int.tryParse(next!.split('=')[1].split('&')[0]) : null,
);
}
String _makeDescriptionText(List<PokemonTypeDto> types) {
return 'Types: ${types.map((type) => type.type.name).join(', ')}';
extension PokemonDataDtoToModel on PokemonDataDto {
CardData toDomain() {
final id = url?.split('/')[6] ?? 'UNKNOWN';
final imageUrl = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/$id.png';
return CardData(
name ?? 'UNKNOWN',
imageUrl: imageUrl,
descriptionText: 'ID: $id',
id: id,
);
}
}
extension PokemonDetailsDtoToModel on PokemonDetailsDto {
String toDescriptionText() {
final abilitiesText = abilities?.map((ability) => ability.ability?.name ?? 'UNKNOWN').join(', ') ?? 'UNKNOWN';
return 'Height: ${height ?? 'UNKNOWN'} cm, Weight: ${weight ?? 'UNKNOWN'} kg, Abilities: $abilitiesText';
}
}

View File

@ -1 +1,72 @@
import 'package:dio/dio.dart';
import 'package:mobilki_lab1/data/dtos/pokemon_dto.dart';
import 'package:mobilki_lab1/data/mappers/pokemon_mapper.dart';
import 'package:mobilki_lab1/data/repositories/api_interface.dart';
import 'package:mobilki_lab1/domain/models/home.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class PokeRepository extends ApiInterface {
static final Dio _dio = Dio()
..interceptors.add(PrettyDioLogger(
requestHeader: true,
requestBody: true,
));
static const String _baseUrl = 'https://pokeapi.co/api/v2';
List<PokemonDataDto> _allPokemon = [];
bool _isAllPokemonLoaded = false;
@override
Future<HomeData?> loadData({
OnErrorCallback? onError,
String? q,
int page = 1,
int pageSize = 25,
}) async {
try {
if (!_isAllPokemonLoaded) {
final String url = '$_baseUrl/pokemon';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
url,
queryParameters: {
'offset': (page - 1) * pageSize,
'limit': pageSize,
},
);
final PokemonDto dto = PokemonDto.fromJson(response.data as Map<String, dynamic>);
_allPokemon = dto.results ?? [];
_isAllPokemonLoaded = true;
}
final List<PokemonDataDto> filteredPokemon = q != null && q.isNotEmpty
? _allPokemon.where((pokemon) => pokemon.name!.contains(q)).toList()
: _allPokemon;
final int startIndex = (page - 1) * pageSize;
final int endIndex = startIndex + pageSize;
if (startIndex >= filteredPokemon.length) {
return HomeData(
data: [],
nextPage: null,
);
}
final List<PokemonDataDto> paginatedPokemon = filteredPokemon.sublist(
startIndex,
endIndex > filteredPokemon.length ? filteredPokemon.length : endIndex,
);
final HomeData data = HomeData(
data: paginatedPokemon.map((e) => e.toDomain()).toList(),
nextPage: endIndex < filteredPokemon.length ? page + 1 : null,
);
return data;
} on DioException catch (e) {
onError?.call(e.error?.toString());
return null;
}
}
}

View File

@ -2,6 +2,7 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobilki_lab1/data/repositories/pokemon_repository.dart';
import 'package:mobilki_lab1/presentation/home_page/bloc/bloc.dart';
import 'package:mobilki_lab1/presentation/home_page/home_page.dart';
import 'package:mobilki_lab1/presentation/like_bloc/like_bloc.dart';
@ -34,15 +35,15 @@ class MyApp extends StatelessWidget {
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: RepositoryProvider<PotterRepository>(
home: RepositoryProvider<PokeRepository>(
lazy: true,
create: (_) => PotterRepository(),
create: (_) => PokeRepository(),
child: BlocProvider<LikeBloc>(
lazy: false,
create: (context) => LikeBloc(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<PotterRepository>()),
create: (context) => HomeBloc(context.read<PokeRepository>()),
child: const MyHomePage(title: 'Чубыкина Полина Павловна'),
),
),

View File

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

View File

@ -27,7 +27,8 @@ class _$LocaleStateCWProxyImpl implements _$LocaleStateCWProxy {
final LocaleState _value;
@override
LocaleState currentLocale(Locale currentLocale) => this(currentLocale: currentLocale);
LocaleState currentLocale(Locale currentLocale) =>
this(currentLocale: currentLocale);
@override
@ -41,10 +42,11 @@ class _$LocaleStateCWProxyImpl implements _$LocaleStateCWProxy {
Object? currentLocale = const $CopyWithPlaceholder(),
}) {
return LocaleState(
currentLocale: currentLocale == const $CopyWithPlaceholder() || currentLocale == null
? _value.currentLocale
// ignore: cast_nullable_to_non_nullable
: currentLocale as Locale,
currentLocale:
currentLocale == const $CopyWithPlaceholder() || currentLocale == null
? _value.currentLocale
// ignore: cast_nullable_to_non_nullable
: currentLocale as Locale,
);
}
}