lab5-6 done

This commit is contained in:
katana 2024-10-29 16:33:19 +03:00
parent be3523c66c
commit fc356b0554
19 changed files with 642 additions and 46 deletions

View File

@ -0,0 +1,22 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
class Debounce {
factory Debounce() => _instance;
Debounce._();
static final Debounce _instance = Debounce._();
static Timer? _timer;
static void run(
VoidCallback action, {
Duration delay = const Duration(milliseconds: 500),
}) {
_timer?.cancel();
_timer = Timer(delay, action);
}
}

View File

@ -0,0 +1,53 @@
import 'package:json_annotation/json_annotation.dart';
part 'cats_dto.g.dart';
@JsonSerializable(createToJson: false)
class CatDataDto {
@JsonKey(name: '_id')
final String? id;
final List<String>? tags;
const CatDataDto({this.id, this.tags});
factory CatDataDto.fromJson(Map<String, dynamic> json) =>
_$CatDataDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class CatsDto {
final List<CatDataDto>? data;
final MetaDto? meta;
const CatsDto({
this.data,
this.meta,
});
factory CatsDto.fromJson(Map<String, dynamic> json) =>
_$CatsDtoFromJson(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

@ -0,0 +1,34 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'cats_dto.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CatDataDto _$CatDataDtoFromJson(Map<String, dynamic> json) => CatDataDto(
id: json['_id'] as String?,
tags: (json['tags'] as List<dynamic>?)?.map((e) => e as String).toList(),
);
CatsDto _$CatsDtoFromJson(Map<String, dynamic> json) => CatsDto(
data: (json['data'] as List<dynamic>?)
?.map((e) => CatDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
meta: json['meta'] == null
? null
: MetaDto.fromJson(json['meta'] as Map<String, dynamic>),
);
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

@ -0,0 +1,20 @@
import 'package:pmu_lab_1/data/dtos/cats_dto.dart';
import 'package:pmu_lab_1/domain/models/card.dart';
import '../../domain/models/home.dart';
extension CatsDtoToModel on CatsDto {
HomeData toDomain({int currentPage = 1, int pageSize = 10}) => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: (data != null && data?.length == pageSize) ? currentPage + 1 : null,
);
}
extension CatDataDtoToModel on CatDataDto {
CardData toDomain() => CardData(
tags?.first ?? 'Ноунейм кот',
imageUrl: 'https://cataas.com/cat/$id',
descriptionText: tags?.join(', ') ?? '',
);
}

View File

@ -0,0 +1,7 @@
import 'package:pmu_lab_1/domain/models/home.dart';
typedef OnErrorCallback = void Function(String? error);
abstract class ApiInterface {
Future<HomeData?> loadData({OnErrorCallback? onError});
}

View File

@ -0,0 +1,49 @@
import 'package:pmu_lab_1/data/dtos/cats_dto.dart';
import 'package:pmu_lab_1/domain/models/card.dart';
import 'package:pmu_lab_1/domain/models/home.dart';
import 'package:pmu_lab_1/data/mappers/cats_mapper.dart';
import 'package:pmu_lab_1/data/repositories/api_interface.dart';
import 'package:dio/dio.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class CatsRepository extends ApiInterface {
static final Dio _dio = Dio()
..interceptors.add(PrettyDioLogger(
requestHeader: true,
requestBody: true,
));
static const baseUrl = 'https://cataas.com/api';
@override
Future<HomeData?> loadData({
OnErrorCallback? onError,
String? q,
int page = 1,
int pageSize = 10,
}) async {
try {
const String url = '$baseUrl/cats';
final Response<dynamic> response = await _dio.get<List<dynamic>>(
url,
queryParameters: {
'tags': q,
'skip': (page - 1) * pageSize,
'limit': pageSize,
},
);
final List<CatDataDto> dtoList = (response.data as List<dynamic>)
.map((json) => CatDataDto.fromJson(json as Map<String, dynamic>))
.toList();
final List<CardData>? data = dtoList.map((e) => e.toDomain()).toList();
int? nextPage = (dtoList.length == pageSize) ? page + 1 : null;
return HomeData(data: data, nextPage: nextPage);
} on DioException catch (e) {
onError?.call(e.error.toString());
return null;
}
}
}

View File

@ -0,0 +1,20 @@
import 'package:pmu_lab_1/domain/models/card.dart';
import 'package:pmu_lab_1/data/repositories/api_interface.dart';
import 'package:pmu_lab_1/domain/models/home.dart';
class MockRepository extends ApiInterface {
@override
Future<HomeData?> loadData({OnErrorCallback? onError}) async {
final data = [
CardData('Cat 1',
descriptionText: 'About cat 1',
imageUrl:
'https://hankpets.com/wp-content/uploads/2024/06/Everything-You-Need-to-Know-About-Persian-Cats.jpg'),
CardData('Cat 2',
descriptionText: 'About cat 2',
imageUrl:
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcST4vFqkon9beoNKaEGwJsaFJTR7l61rtMhYJgvHEWuc0QT5ajF'),
];
return HomeData(data: data);
}
}

View File

@ -0,0 +1,8 @@
import 'card.dart';
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.nextPage});
}

View File

@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu_lab_1/data/repositories/cats_repository.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/bloc.dart';
import 'package:pmu_lab_1/presentation/home_page/home_page.dart';
void main() {
@ -16,7 +19,15 @@ class MyApp extends StatelessWidget {
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Teryokhin Andrey Sergeevich'),
home: RepositoryProvider<CatsRepository>(
lazy: true,
create: (_) => CatsRepository(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<CatsRepository>()),
child: const MyHomePage(title: 'PIbd31 Teryokhin'),
)
)
);
}
}

View File

@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
class ErrorDialog extends StatelessWidget {
final String? error;
const ErrorDialog(this.error, {super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Material(
color: Colors.transparent,
child: Container(
margin: const EdgeInsets.all(36),
padding: const EdgeInsets.all(20),
decoration: const BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error, color: Colors.white),
const SizedBox(height: 12),
Text(
error ?? 'UNKNOWN',
style: Theme.of(context)
.textTheme
.bodyLarge
?.copyWith(color: Colors.white),
),
],
),
),
),
);
}
}

View File

@ -0,0 +1,12 @@
import 'package:flutter/material.dart';
import 'package:pmu_lab_1/presentation/dialogs/error_dialog.dart';
void showErrorDialog(
BuildContext context, {
required String? error,
}) {
showDialog(
context: context,
builder: (_) => ErrorDialog(error),
);
}

View File

@ -0,0 +1,38 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu_lab_1/data/repositories/cats_repository.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/events.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final CatsRepository repo;
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
void _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
if (event.nextPage == null) {
emit(state.copyWith(isLoading: true));
} else {
emit(state.copyWith(isPaginationLoading: true));
}
String? error;
final data = await repo.loadData(
q: event.search,
page: event.nextPage ?? 1,
onError: (e) => error = e,
);
if (event.nextPage != null) {
data?.data?.insertAll(0, state.data?.data ?? []);
}
emit(state.copyWith(
isLoading: false,
isPaginationLoading: false,
data: data,
error: error,
));
}
}

View File

@ -0,0 +1,10 @@
abstract class HomeEvent {
const HomeEvent();
}
class HomeLoadDataEvent extends HomeEvent {
final String? search;
final int? nextPage;
const HomeLoadDataEvent({this.search, this.nextPage});
}

View File

@ -0,0 +1,28 @@
import 'package:equatable/equatable.dart';
import 'package:pmu_lab_1/domain/models/home.dart';
import 'package:copy_with_extension/copy_with_extension.dart';
part 'state.g.dart';
@CopyWith()
class HomeState extends Equatable {
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
final String? error;
const HomeState({
this.data,
this.isLoading = false,
this.isPaginationLoading = false,
this.error,
});
@override
List<Object?> get props => [
data,
isLoading,
isPaginationLoading,
error,
];
}

View File

@ -0,0 +1,92 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'state.dart';
// **************************************************************************
// CopyWithGenerator
// **************************************************************************
abstract class _$HomeStateCWProxy {
HomeState data(HomeData? data);
HomeState isLoading(bool isLoading);
HomeState isPaginationLoading(bool isPaginationLoading);
HomeState error(String? error);
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `HomeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// HomeState(...).copyWith(id: 12, name: "My name")
/// ````
HomeState call({
HomeData? data,
bool? isLoading,
bool? isPaginationLoading,
String? error,
});
}
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfHomeState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfHomeState.copyWith.fieldName(...)`
class _$HomeStateCWProxyImpl implements _$HomeStateCWProxy {
const _$HomeStateCWProxyImpl(this._value);
final HomeState _value;
@override
HomeState data(HomeData? data) => this(data: data);
@override
HomeState isLoading(bool isLoading) => this(isLoading: isLoading);
@override
HomeState isPaginationLoading(bool isPaginationLoading) =>
this(isPaginationLoading: isPaginationLoading);
@override
HomeState error(String? error) => this(error: error);
@override
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `HomeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
///
/// Usage
/// ```dart
/// HomeState(...).copyWith(id: 12, name: "My name")
/// ````
HomeState call({
Object? data = const $CopyWithPlaceholder(),
Object? isLoading = const $CopyWithPlaceholder(),
Object? isPaginationLoading = const $CopyWithPlaceholder(),
Object? error = const $CopyWithPlaceholder(),
}) {
return HomeState(
data: data == const $CopyWithPlaceholder()
? _value.data
// ignore: cast_nullable_to_non_nullable
: data as HomeData?,
isLoading: isLoading == const $CopyWithPlaceholder() || isLoading == null
? _value.isLoading
// ignore: cast_nullable_to_non_nullable
: isLoading as bool,
isPaginationLoading:
isPaginationLoading == const $CopyWithPlaceholder() ||
isPaginationLoading == null
? _value.isPaginationLoading
// ignore: cast_nullable_to_non_nullable
: isPaginationLoading as bool,
error: error == const $CopyWithPlaceholder()
? _value.error
// ignore: cast_nullable_to_non_nullable
: error as String?,
);
}
}
extension $HomeStateCopyWith on HomeState {
/// Returns a callable class that can be used as follows: `instanceOfHomeState.copyWith(...)` or like so:`instanceOfHomeState.copyWith.fieldName(...)`.
// ignore: library_private_types_in_public_api
_$HomeStateCWProxy get copyWith => _$HomeStateCWProxyImpl(this);
}

View File

@ -89,24 +89,6 @@ class _CardState extends State<_Card> {
errorBuilder: (_, __, ___) => const Placeholder(),
),
),
Align(
alignment: Alignment.bottomLeft,
child: Container(
decoration: const BoxDecoration(
color: Colors.redAccent,
borderRadius: BorderRadius.only(
topRight: Radius.circular(20),
)),
padding: const EdgeInsets.fromLTRB(8, 2, 8, 2),
child: Text(
'скидка 20%',
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: Colors.black),
),
),
),
],
),
),

View File

@ -1,7 +1,12 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu_lab_1/data/repositories/cats_repository.dart';
import 'package:pmu_lab_1/presentation/details_page/details_page.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/events.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/bloc.dart';
import 'package:pmu_lab_1/presentation/home_page/bloc/state.dart';
import '../../components/utils/debounce.dart';
import '../../domain/models/card.dart';
part 'card.dart';
@ -16,7 +21,6 @@ class MyHomePage extends StatefulWidget {
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
@ -28,39 +32,108 @@ class _MyHomePageState extends State<MyHomePage> {
}
}
class Body extends StatelessWidget {
class Body extends StatefulWidget {
const Body({super.key});
@override
Widget build(BuildContext context) {
final data = [
CardData('Cat 1',
descriptionText: 'About cat 1',
imageUrl:
'https://hankpets.com/wp-content/uploads/2024/06/Everything-You-Need-to-Know-About-Persian-Cats.jpg'),
CardData('Cat 2',
descriptionText: 'About cat 2',
imageUrl:
'https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcST4vFqkon9beoNKaEGwJsaFJTR7l61rtMhYJgvHEWuc0QT5ajF'),
];
State<Body> createState() => _BodyState();
}
return Center(
child: SingleChildScrollView(
class _BodyState extends State<Body> {
final searchController = TextEditingController();
final scrollController = ScrollController();
// late Future<List<CardData>?> data;
final repo = CatsRepository();
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState();
}
@override
void dispose() {
searchController.dispose();
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: data
.map((data) => _Card.fromData(
children: [
Padding(
padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField(
controller: searchController,
onChanged: (search) {
Debounce.run(() => context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: search)));
},
),
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.error != null
? Text(
state.error ?? '',
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(color: Colors.red),
)
: state.isLoading
? const CircularProgressIndicator()
: Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
child: ListView.builder(
controller: scrollController,
padding: EdgeInsets.zero,
itemCount: state.data?.data?.length ?? 0,
itemBuilder: (context, index) {
final data = state.data?.data?[index];
return data != null
? _Card.fromData(
data,
onLike: (String title, bool isLiked) =>
_showSnackBar(context, title, isLiked),
_showSnackBar(
context, title, isLiked),
onTap: () => _navToDetails(context, data),
))
.toList(),
)
: const SizedBox.shrink();
},
),
),
),
),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink(),
),
],
),
);
}
Future<void> _onRefresh() {
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
void _navToDetails(BuildContext context, CardData data) {
Navigator.push(
context,
@ -80,4 +153,17 @@ class Body extends StatelessWidget {
));
});
}
void _onNextPageListener() {
if (scrollController.offset >= scrollController.position.maxScrollExtent) {
// preventing multiple pagination request on multiple swipes
final bloc = context.read<HomeBloc>();
if (!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent(
search: searchController.text,
nextPage: bloc.state.data?.nextPage,
));
}
}
}
}

View File

@ -38,6 +38,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.11.0"
bloc:
dependency: transitive
description:
name: bloc
sha256: "106842ad6569f0b60297619e9e0b1885c2fb9bf84812935490e6c5275777804e"
url: "https://pub.dev"
source: hosted
version: "8.1.4"
boolean_selector:
dependency: transitive
description:
@ -158,6 +166,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
copy_with_extension:
dependency: transitive
description:
name: copy_with_extension
sha256: fbcf890b0c34aedf0894f91a11a579994b61b4e04080204656b582708b5b1125
url: "https://pub.dev"
source: hosted
version: "5.0.4"
copy_with_extension_gen:
dependency: "direct main"
description:
name: copy_with_extension_gen
sha256: "51cd11094096d40824c8da629ca7f16f3b7cea5fc44132b679617483d43346b0"
url: "https://pub.dev"
source: hosted
version: "5.0.4"
crypto:
dependency: transitive
description:
@ -182,6 +206,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.7"
dio:
dependency: "direct main"
description:
name: dio
sha256: "5598aa796bbf4699afd5c67c0f5f6e2ed542afc956884b9cd58c306966efc260"
url: "https://pub.dev"
source: hosted
version: "5.7.0"
dio_web_adapter:
dependency: transitive
description:
name: dio_web_adapter
sha256: "33259a9276d6cea88774a0000cfae0d861003497755969c92faa223108620dc8"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
equatable:
dependency: "direct main"
description:
name: equatable
sha256: c2b87cb7756efdf69892005af546c56c0b5037f54d2a88269b4f347a505e3ca2
url: "https://pub.dev"
source: hosted
version: "2.0.5"
fake_async:
dependency: transitive
description:
@ -211,6 +259,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_bloc:
dependency: "direct main"
description:
name: flutter_bloc
sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a
url: "https://pub.dev"
source: hosted
version: "8.1.6"
flutter_lints:
dependency: "direct dev"
description:
@ -376,6 +432,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
package_config:
dependency: transitive
description:
@ -400,6 +464,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.5.1"
pretty_dio_logger:
dependency: "direct main"
description:
name: pretty_dio_logger
sha256: "36f2101299786d567869493e2f5731de61ce130faa14679473b26905a92b6407"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
provider:
dependency: transitive
description:
name: provider
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
url: "https://pub.dev"
source: hosted
version: "6.1.2"
pub_semver:
dependency: transitive
description:

View File

@ -37,6 +37,12 @@ dependencies:
cupertino_icons: ^1.0.8
json_annotation: ^4.8.1
dio: ^5.4.2+1
pretty_dio_logger: ^1.3.1
equatable: ^2.0.5
flutter_bloc: ^8.1.6
copy_with_extension_gen: ^5.0.4
dev_dependencies:
flutter_test: