lab6 - готова

This commit is contained in:
DyCTaTOR 2024-10-30 22:39:56 +04:00
parent 89d2b1786d
commit 40ecf64dfb
16 changed files with 336 additions and 57 deletions

View File

@ -0,0 +1,20 @@
import 'dart:async';
import 'dart:ui';
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

@ -1,17 +1,36 @@
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
import 'package:labs/CourseStatus.dart';
part 'characters_dto.g.dart'; part 'characters_dto.g.dart';
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class CharactersDto{ class CharactersDto{
final List<CharacterDataDto>? data; final List<CharacterDataDto>? data;
final MetaDto? meta;
const CharactersDto({this.data}); const CharactersDto({this.data, this.meta});
factory CharactersDto.fromJson(Map<String, dynamic> json) => _$CharactersDtoFromJson(json); factory CharactersDto.fromJson(Map<String, dynamic> json) => _$CharactersDtoFromJson(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);
}
@JsonSerializable(createToJson: false) @JsonSerializable(createToJson: false)
class CharacterDataDto { class CharacterDataDto {
final String? id; final String? id;

View File

@ -11,6 +11,22 @@ CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) =>
data: (json['data'] as List<dynamic>?) data: (json['data'] as List<dynamic>?)
?.map((e) => CharacterDataDto.fromJson(e as Map<String, dynamic>)) ?.map((e) => CharacterDataDto.fromJson(e as Map<String, dynamic>))
.toList(), .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(),
); );
CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) => CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) =>

View File

@ -2,6 +2,7 @@
import 'package:labs/data/dtos/characters_dto.dart'; import 'package:labs/data/dtos/characters_dto.dart';
import 'package:labs/domain/models/Student.dart'; import 'package:labs/domain/models/Student.dart';
import 'package:labs/domain/models/home.dart';
extension CharacterDataDtoToModel on CharacterDataDto{ extension CharacterDataDtoToModel on CharacterDataDto{
Student toDomain() => Student( Student toDomain() => Student(
@ -11,3 +12,10 @@ extension CharacterDataDtoToModel on CharacterDataDto{
image: attributes?.image ?? 'https://gryazoveckij-r19.gosweb.gosuslugi.ru/netcat_files/460/2008/net_foto_muzh.jpg' image: attributes?.image ?? 'https://gryazoveckij-r19.gosweb.gosuslugi.ru/netcat_files/460/2008/net_foto_muzh.jpg'
); );
} }
extension CharactersDtoToModel on CharactersDto {
HomeData toDomain() => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: meta?.pagination?.next,
);
}

View File

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

View File

@ -1,6 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:labs/presentation/home_page/bloc/bloc.dart';
import 'package:labs/presentation/home_page/home_page.dart'; import 'package:labs/presentation/home_page/home_page.dart';
import 'CourseStatus.dart'; import 'package:labs/repo/potter_repo.dart';
import 'University.dart'; import 'University.dart';
import 'domain/models/Student.dart'; import 'domain/models/Student.dart';
@ -51,17 +53,22 @@ class _UniversityScreenState extends State<UniversityScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return MaterialApp(
appBar: AppBar( title: 'Строев Владимир, ПИбд-32',
title: Text('Строев Владимир, ПИбд-32'), debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.orangeAccent),
useMaterial3: true,
), ),
body: Column( home: RepositoryProvider<PotterRepo>(
children: [ lazy: true,
Expanded( create: (_) => PotterRepo(),
child: MyHomePage(), child: BlocProvider<HomeBloc>(
), lazy: false,
], create: (context) => HomeBloc(context.read<PotterRepo>()),
child: const MyHomePage(),
), ),
)
); );
} }
} }

View File

@ -0,0 +1,39 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:labs/presentation/home_page/bloc/events.dart';
import 'package:labs/presentation/home_page/bloc/state.dart';
import 'package:labs/repo/potter_repo.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final PotterRepo repo;
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
Future<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,42 @@
import 'package:equatable/equatable.dart';
import 'package:copy_with_extension/copy_with_extension.dart';
import '../../../domain/models/home.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,
});
HomeState copyWith({
HomeData? data,
bool? isLoading,
bool? isPaginationLoading,
String? error,
}) =>
HomeState(
data: data ?? this.data,
isLoading: isLoading ?? this.isLoading,
isPaginationLoading: isPaginationLoading ?? this.isPaginationLoading,
error: error ?? this.error,
);
@override
List<Object?> get props => [
data,
isLoading,
isPaginationLoading,
error,
];
}

View File

@ -1,9 +1,13 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:labs/presentation/details_page/details_page.dart'; import 'package:labs/presentation/details_page/details_page.dart';
import 'package:labs/repo/mock_repo.dart'; import 'package:labs/presentation/home_page/bloc/events.dart';
import 'package:labs/repo/potter_repo.dart'; import 'package:labs/repo/potter_repo.dart';
import '../../components/utils/debounce.dart';
import '../../domain/models/Student.dart'; import '../../domain/models/Student.dart';
import 'bloc/bloc.dart';
import 'bloc/state.dart';
part 'card.dart'; part 'card.dart';
class MyHomePage extends StatefulWidget { class MyHomePage extends StatefulWidget {
@ -14,14 +18,39 @@ class MyHomePage extends StatefulWidget {
} }
class _MyHomePageState extends State<MyHomePage> { class _MyHomePageState extends State<MyHomePage> {
final TextEditingController searchController = TextEditingController(); final searchController = TextEditingController();
final scrollController = ScrollController();
final PotterRepo repo = PotterRepo(); final PotterRepo repo = PotterRepo();
late Future<List<Student>?> data; late Future<List<Student>?> data;
@override @override
void initState() { void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState(); super.initState();
data = repo.loadData(null); }
void _onNextPageListener(){
if(scrollController.offset > scrollController.position.maxScrollExtent) {
final bloc = context.read<HomeBloc>();
if(!bloc.state.isPaginationLoading) {
bloc.add(HomeLoadDataEvent (
search: searchController.text,
nextPage: bloc.state.data?.nextPage,
));
}
}
}
@override
void dispose(){
searchController.dispose();
scrollController.dispose();
super.dispose();
} }
@override @override
@ -35,33 +64,32 @@ class _MyHomePageState extends State<MyHomePage> {
child: CupertinoSearchTextField( child: CupertinoSearchTextField(
controller: searchController, controller: searchController,
onChanged: (search) { onChanged: (search) {
setState(() { Debounce.run(() => context.read<HomeBloc>().add(HomeLoadDataEvent(search: search)));
data = repo.loadData(search);
});
}, },
), ),
), ),
Expanded( BlocBuilder<HomeBloc, HomeState>(
child: Center( builder: (context, state) => state.isLoading
child: FutureBuilder<List<Student>?>( ? const CircularProgressIndicator()
future: data, : Expanded(
builder: (context, snapshot) => SingleChildScrollView( child: RefreshIndicator(
child: snapshot.hasData onRefresh: _onRefresh,
? Column( child: ListView.builder(
mainAxisAlignment: MainAxisAlignment.center, padding: EdgeInsets.zero,
children: snapshot.data!.map((e) { itemCount: state.data?.data?.length ?? 0,
return _Card.fromData( itemBuilder: (context, index) {
e, final data = state.data?.data?[index];
return data != null
? _Card.fromData(data,
onLike: (title, isLiked) => onLike: (title, isLiked) =>
_showSnackBar(context, title, isLiked), _showSnackBar(context, title, isLiked),
onTap: () => _navToDetails(context, e), onTap: () => _navToDetails(context, data),
);
}).toList(),
) )
: const CircularProgressIndicator(), : const SizedBox.shrink();
), },
), ),
), ),
)
), ),
], ],
), ),
@ -75,6 +103,11 @@ class _MyHomePageState extends State<MyHomePage> {
); );
} }
Future<void> _onRefresh() {
context.read<HomeBloc>().add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
void _showSnackBar(BuildContext context, String title, bool isLiked) { void _showSnackBar(BuildContext context, String title, bool isLiked) {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar( ScaffoldMessenger.of(context).showSnackBar(SnackBar(

View File

@ -1,6 +1,8 @@
import '../domain/models/Student.dart'; import '../domain/models/home.dart';
typedef OnErrorCallback = void Function(String? error);
abstract class ApiInterface{ abstract class ApiInterface{
Future<List<Student>?> loadData(String? q); Future<HomeData?> loadData({OnErrorCallback? onError});
} }

View File

@ -1,15 +1,19 @@
import 'package:labs/CourseStatus.dart'; import 'package:labs/CourseStatus.dart';
import 'package:labs/domain/models/Student.dart'; import 'package:labs/domain/models/Student.dart';
import '../domain/models/home.dart';
import 'api_interface.dart'; import 'api_interface.dart';
class MockRepo extends ApiInterface { class MockRepo extends ApiInterface {
@override @override
Future<List<Student>?> loadData(String? q) async { Future<HomeData?> loadData({OnErrorCallback? onError}) async {
return [ return HomeData (
);
/*return [
Student('Stroev V.', 19, [CourseStatus.Biology.name]), Student('Stroev V.', 19, [CourseStatus.Biology.name]),
Student('Samoilov K.', 20, [CourseStatus.Chemistry.name]), Student('Samoilov K.', 20, [CourseStatus.Chemistry.name]),
Student('Belov M.', 21, [CourseStatus.ComputerScience.name]), Student('Belov M.', 21, [CourseStatus.ComputerScience.name]),
]; ];*/
} }
} }

View File

@ -4,9 +4,10 @@ import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../data/dtos/characters_dto.dart'; import '../data/dtos/characters_dto.dart';
import '../domain/models/Student.dart'; import '../domain/models/Student.dart';
import '../domain/models/home.dart';
import 'api_interface.dart'; import 'api_interface.dart';
class PotterRepo extends ApiInterface{ class PotterRepo extends ApiInterface {
static final Dio _dio = Dio() static final Dio _dio = Dio()
..interceptors.add(PrettyDioLogger( ..interceptors.add(PrettyDioLogger(
requestHeader: true, requestHeader: true,
@ -16,16 +17,27 @@ class PotterRepo extends ApiInterface{
static const String _baseUrl = 'https://api.potterdb.com'; static const String _baseUrl = 'https://api.potterdb.com';
@override @override
Future<List<Student>?> loadData(String? q) async { Future<HomeData?> loadData(
{OnErrorCallback? onError, String? q, int page = 1, int pageSize = 25}) async {
try {
const String url = '$_baseUrl/v1/characters'; const String url = '$_baseUrl/v1/characters';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(url, final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
queryParameters: q != null ? {'filter[name_cont]': q} : null,); url,
queryParameters: {
'filter[name_count]': q,
'page[number]': page,
'page[size]': pageSize,
},
);
final CharactersDto dto = CharactersDto.fromJson(response.data as Map<String, dynamic>); final CharactersDto dto = CharactersDto.fromJson(
final List<Student>? data = dto.data?.map((e) => e.toDomain()).toList(); response.data as Map<String, dynamic>);
final HomeData data = dto.toDomain();
return data; return data;
} on DioException catch (e) {
onError?.call(e.error?.toString());
return null;
}
} }
} }

View File

@ -38,6 +38,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.11.0" version: "2.11.0"
bloc:
dependency: transitive
description:
name: bloc
sha256: "106842ad6569f0b60297619e9e0b1885c2fb9bf84812935490e6c5275777804e"
url: "https://pub.dev"
source: hosted
version: "8.1.4"
boolean_selector: boolean_selector:
dependency: transitive dependency: transitive
description: description:
@ -138,10 +146,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: code_builder name: code_builder
sha256: f692079e25e7869c14132d39f223f8eec9830eb76131925143b2129c4bb01b37 sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.10.0" version: "4.10.1"
collection: collection:
dependency: transitive dependency: transitive
description: description:
@ -158,6 +166,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.1.2" version: "3.1.2"
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: crypto:
dependency: transitive dependency: transitive
description: description:
@ -198,6 +222,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" 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: fake_async:
dependency: transitive dependency: transitive
description: description:
@ -227,6 +259,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" 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: flutter_lints:
dependency: "direct dev" dependency: "direct dev"
description: description:
@ -392,6 +432,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.0" version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
package_config: package_config:
dependency: transitive dependency: transitive
description: description:
@ -424,6 +472,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.0" version: "1.4.0"
provider:
dependency: transitive
description:
name: provider
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
url: "https://pub.dev"
source: hosted
version: "6.1.2"
pub_semver: pub_semver:
dependency: transitive dependency: transitive
description: description:

View File

@ -39,6 +39,9 @@ dependencies:
json_annotation: ^4.9.0 json_annotation: ^4.9.0
dio: ^5.4.2+1 dio: ^5.4.2+1
pretty_dio_logger: ^1.3.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: dev_dependencies:
flutter_test: flutter_test:

View File

@ -13,7 +13,7 @@ import 'package:labs/main.dart';
void main() { void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async { testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame. // Build our app and trigger a frame.
await tester.pumpWidget(const MyApp()); await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0. // Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget); expect(find.text('0'), findsOneWidget);