6 lab architecture, pagination, searchController

This commit is contained in:
sardq 2024-10-16 14:37:36 +04:00
parent d1b552ad5d
commit cd022a58d7
16 changed files with 300 additions and 101 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 @@
typedef OnErrorCallback = void Function(String? error)?;

View File

@ -5,12 +5,26 @@ part 'mangas_dto.g.dart';
@JsonSerializable(createToJson: false)
class MangasDto {
final List<MangaDataDto>? data;
const MangasDto({this.data});
final MangaPaginationDto? pagination;
const MangasDto({this.data, this.pagination});
factory MangasDto.fromJson(Map<String, dynamic> json) =>
_$MangasDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class MangaPaginationDto {
@JsonKey(name: 'current_page')
final int? currentPage;
@JsonKey(name: 'has_next_page')
final bool? hasNextPage;
@JsonKey(name: 'last_visible_page')
final int? lastVisiblePage;
const MangaPaginationDto({this.currentPage, this.hasNextPage, this.lastVisiblePage});
factory MangaPaginationDto.fromJson(Map<String, dynamic> json) =>
_$MangaPaginationDtoFromJson(json);
}
@JsonSerializable(createToJson: false)
class MangaDataDto {

View File

@ -10,6 +10,17 @@ MangasDto _$MangasDtoFromJson(Map<String, dynamic> json) => MangasDto(
data: (json['data'] as List<dynamic>?)
?.map((e) => MangaDataDto.fromJson(e as Map<String, dynamic>))
.toList(),
pagination: json['pagination'] == null
? null
: MangaPaginationDto.fromJson(
json['pagination'] as Map<String, dynamic>),
);
MangaPaginationDto _$MangaPaginationDtoFromJson(Map<String, dynamic> json) =>
MangaPaginationDto(
currentPage: (json['current_page'] as num?)?.toInt(),
hasNextPage: json['has_next_page'] as bool?,
lastVisiblePage: (json['last_visible_page'] as num?)?.toInt(),
);
MangaDataDto _$MangaDataDtoFromJson(Map<String, dynamic> json) => MangaDataDto(

View File

@ -1,5 +1,6 @@
import 'package:flutter_app/data/dtos/mangas_dto.dart';
import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
extension MangaDataDtoMapper on MangaDataDto {
CardData toDomain() => CardData(
@ -9,3 +10,10 @@ extension MangaDataDtoMapper on MangaDataDto {
'Статус: ${status}. Рейтинг: ${score}. Людей поставило оценку: ${scored_by}',
);
}
extension MangasDtoToModel on MangasDto {
HomeData toDomain() => HomeData(
data: data?.map((e) => e.toDomain()).toList(),
nextPage: (pagination?.hasNextPage ?? false)
? ((pagination?.currentPage ?? 0) + 1)
: null);
}

View File

@ -1,5 +1,6 @@
import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/components/utils/error_callback.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
abstract class ApiInterface {
Future<List<CardData>?> loadData();
Future<HomeData?> loadData({OnErrorCallback? onError});
}

View File

@ -1,8 +1,9 @@
import 'package:flutter_app/components/utils/error_callback.dart';
import 'package:flutter_app/data/dtos/mangas_dto.dart';
import 'package:flutter_app/data/mappers/mangas_mapper.dart';
import 'package:flutter_app/data/repositories/api_interface.dart';
import 'package:dio/dio.dart';
import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
class MangaRepository extends ApiInterface {
@ -14,18 +15,28 @@ class MangaRepository extends ApiInterface {
static const String _baseUrl = 'https://api.jikan.moe';
@override
Future<List<CardData>?> loadData({String? q}) async {
Future<HomeData?> loadData({
OnErrorCallback? onError,
String? q,
int page = 1,
int pageSize = 25,
}) async {
try {
const String url = '$_baseUrl/v4/manga';
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
url,
queryParameters: q != null ? {'q': q} : null);
final Response<dynamic> response = await _dio
.get<Map<dynamic, dynamic>>(url, queryParameters: {
'q': q,
'page': page,
'limit': !(pageSize > 25) ? pageSize : 25
});
final MangasDto dto =
MangasDto.fromJson(response.data as Map<String, dynamic>);
final List<CardData>? data = dto.data?.map((e) => e.toDomain()).toList();
final HomeData? data = dto.toDomain();
return data;
} on DioException catch (e) {
onError?.call(e.response?.statusMessage);
return null;
}
}

View File

@ -1,14 +1,18 @@
import 'package:flutter_app/components/utils/error_callback.dart';
import 'package:flutter_app/data/repositories/api_interface.dart';
import 'package:flutter_app/domain/models/carddata.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
class MockRepository extends ApiInterface {
@override
Future<List<CardData>?> loadData() async {
return [
Future<HomeData?> loadData({OnErrorCallback? onError}) async {
return HomeData(
data: [
CardData('JoJos Bizarre Adventure', descriptionText: 'kono dio da', imageUrl: 'https://i1.sndcdn.com/avatars-253MmMf9QZzxVBJi-rvlyeg-t1080x1080.jpg'),
CardData('Example', descriptionText: 'what is this?', imageUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvaBQ6nAedlqvXsh-dLXZi2Gexy1RkDbTUKQ&s'),
CardData('Mock data', descriptionText: 'Mock data description', imageUrl: 'https://cdn-user30887.skyeng.ru/uploads/6692a339c6989979804399.png'),
];
],
);
}
}

View File

@ -1,5 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_app/data/repositories/manga_repository.dart';
import 'package:flutter_app/presentation/home_page/bloc/bloc.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(const MyApp());
@ -14,25 +17,18 @@ class MyApp extends StatelessWidget {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Разубаев Сергей Михайлович'),
home: RepositoryProvider<MangaRepository>(
lazy: true,
create: (_) => MangaRepository(),
child: BlocProvider<HomeBloc>(
lazy: false,
create: (context) => HomeBloc(context.read<MangaRepository>()),
child: const HomePage(),
),
)
);
}
}

View File

@ -0,0 +1,27 @@
import 'package:flutter_app/data/repositories/manga_repository.dart';
import 'package:flutter_app/presentation/home_page/bloc/events.dart';
import 'package:flutter_app/presentation/home_page/bloc/state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState>{
final MangaRepository 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));
}
final data = await repo.loadData(q: event.search, page: event.nextPage ?? 1);
if (event.nextPage != null) {
data?.data?.insertAll(0, state.data?.data ?? []);
}
emit(state.copyWith(data: data, isLoading: false, isPaginationLoading: false));
}
}

View File

@ -0,0 +1,9 @@
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,15 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_app/presentation/home_page/home_page.dart';
class HomeState extends Equatable {
final HomeData? data;
final bool isLoading;
final bool isPaginationLoading;
const HomeState({this.data, this.isLoading = false, this.isPaginationLoading = false});
HomeState copyWith({HomeData? data, bool? isLoading, bool? isPaginationLoading}) => HomeState(
data: data ?? this.data, isLoading: isLoading ?? this.isLoading, isPaginationLoading: isPaginationLoading ?? this.isPaginationLoading);
@override
List<Object?> get props => [data, isLoading, isPaginationLoading];
}

View File

@ -1,48 +1,35 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/components/utils/debounce.dart';
import 'package:flutter_app/data/repositories/manga_repository.dart';
import 'package:flutter_app/data/repositories/mock_repository.dart';
import 'package:flutter_app/presentation/details_page/details_page.dart';
import 'package:flutter_app/presentation/home_page/bloc/bloc.dart';
import 'package:flutter_app/presentation/home_page/bloc/events.dart';
import 'package:flutter_app/presentation/home_page/bloc/state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/models/carddata.dart';
part 'card.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
State<HomePage> createState() => _HomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme
.of(context)
.colorScheme
.inversePrimary,
title: Text(widget.title),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: const Body(),
);
}
}
class Body extends StatefulWidget {
@ -53,6 +40,37 @@ class Body extends StatefulWidget {
}
class _BodyState extends State<Body> {
final scrollController = ScrollController();
final searchController = TextEditingController();
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<HomeBloc>().add(const HomeLoadDataEvent());
});
scrollController.addListener(_onNextPageListener);
super.initState();
}
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();
}
final MangaRepository repo = MangaRepository();
var data = MangaRepository().loadData();
@ -61,10 +79,7 @@ class _BodyState extends State<Body> {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}',
style: Theme
.of(context)
.textTheme
.bodyLarge,
style: Theme.of(context).textTheme.bodyLarge,
),
backgroundColor: Colors.orangeAccent,
duration: const Duration(seconds: 1),
@ -77,9 +92,15 @@ class _BodyState extends State<Body> {
context, CupertinoPageRoute(builder: (context) => DetailsPage(data)));
}
Future<void> _onRefresh() {
context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: searchController.text));
return Future.value(null);
}
@override
Widget build(BuildContext context) {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
child: Column(
@ -87,34 +108,49 @@ Widget build(BuildContext context) {
Padding(
padding: const EdgeInsets.all(12),
child: CupertinoSearchTextField(
controller: searchController,
onChanged: (search) {
setState(() {
data = repo.loadData(q:search);
});
},
),
),
Expanded(child: Center(
child: FutureBuilder<List<CardData>?>(
future: data,
builder: (context, snapshot) =>
SingleChildScrollView(
child: snapshot.hasData ? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: snapshot.data!.map((data) {
return _Card.fromData(data,
onLike: (String title, bool isLiked) =>
_showSnackbar(context, title, isLiked),
onTap: () => _navToDetails(context, data),);
}).toList() ?? [],
Debounce.run(() => context
.read<HomeBloc>()
.add(HomeLoadDataEvent(search: search)));
})),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isLoading
? 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: (title, isLiked) =>
_showSnackbar(
context, title, isLiked),
onTap: () =>
_navToDetails(context, data),
)
: const CircularProgressIndicator(),
: const SizedBox.shrink();
}),
),
),
),
)
)),
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) => state.isPaginationLoading
? const CircularProgressIndicator()
: const SizedBox.shrink())
],
));
}}
}
}
class HomeData {
final List<CardData>? data;
final int? nextPage;
HomeData({this.data, this.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:
@ -154,18 +162,18 @@ packages:
dependency: transitive
description:
name: convert
sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592"
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.1"
version: "3.1.2"
crypto:
dependency: transitive
description:
name: crypto
sha256: ec30d999af904f33454ba22ed9a86162b35e52b44ac4807d1d93c288041d7d27
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
url: "https://pub.dev"
source: hosted
version: "3.0.5"
version: "3.0.6"
cupertino_icons:
dependency: "direct main"
description:
@ -198,6 +206,14 @@ packages:
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:
@ -218,15 +234,23 @@ packages:
dependency: transitive
description:
name: fixnum
sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1"
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.0"
version: "1.1.1"
flutter:
dependency: "direct main"
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:
@ -392,6 +416,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:
@ -424,6 +456,14 @@ packages:
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

@ -15,6 +15,10 @@ dependencies:
json_annotation: ^4.8.1
dio: ^5.4.2+1
pretty_dio_logger: ^1.3.1
equatable: ^2.0.5
flutter_bloc: ^8.1.5
dev_dependencies:
flutter_test:
sdk: flutter

View File

@ -8,7 +8,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pmu_labs/main.dart';
import 'package:flutter_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {