laboratory_6
This commit is contained in:
parent
0bee6d7055
commit
fb76d00505
@ -1,33 +0,0 @@
|
|||||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
|
||||||
|
|
||||||
part of 'houses_dto.dart';
|
|
||||||
|
|
||||||
// **************************************************************************
|
|
||||||
// JsonSerializableGenerator
|
|
||||||
// **************************************************************************
|
|
||||||
|
|
||||||
|
|
||||||
HousesDto _$HousesDtoFromJson(Map<String, dynamic> json) =>
|
|
||||||
HousesDto(
|
|
||||||
data: (json['data'] as List<dynamic>?)
|
|
||||||
?.map((e) => HouseDataDto.fromJson(e as Map<String, dynamic>))
|
|
||||||
.toList(),
|
|
||||||
);
|
|
||||||
|
|
||||||
HouseDataDto _$HouseDataDtoFromJson(Map<String, dynamic> json) =>
|
|
||||||
HouseDataDto(
|
|
||||||
json['id'] as String?,
|
|
||||||
json['attributes'] == null
|
|
||||||
? null
|
|
||||||
: HouseAttributesDataDto.fromJson(
|
|
||||||
json['attributes'] as Map<String, dynamic>),
|
|
||||||
);
|
|
||||||
|
|
||||||
HouseAttributesDataDto _$HouseAttributesDataDtoFromJson(
|
|
||||||
Map<String, dynamic> json) =>
|
|
||||||
HouseAttributesDataDto(
|
|
||||||
json['name'] as String?,
|
|
||||||
json['location'] as String?,
|
|
||||||
json['image'] as String?,
|
|
||||||
json['description'] as String?,
|
|
||||||
);
|
|
@ -1,17 +1,41 @@
|
|||||||
import 'package:json_annotation/json_annotation.dart';
|
import 'package:json_annotation/json_annotation.dart';
|
||||||
|
|
||||||
// dart run build_runner build --delete-conflicting-outputs
|
// dart run build_runner build --delete-conflicting-outputs
|
||||||
|
// flutter pub run build_runner build --delete-conflicting-outputs
|
||||||
|
|
||||||
part 'house_dto_json.dart';
|
part 'houses_dto.g.dart';
|
||||||
|
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
class HousesDto {
|
class HousesDto {
|
||||||
final List<HouseDataDto>? data;
|
final List<HouseDataDto>? data;
|
||||||
|
final MetaDto? meta;
|
||||||
|
|
||||||
const HousesDto({this.data});
|
const HousesDto({this.data, this.meta});
|
||||||
|
|
||||||
factory HousesDto.fromJson(Map<String, dynamic> json) => _$HousesDtoFromJson(json);
|
factory HousesDto.fromJson(Map<String, dynamic> json) =>
|
||||||
|
_$HousesDtoFromJson(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.last, this.next});
|
||||||
|
|
||||||
|
factory PaginationDto.fromJson(Map<String, dynamic> json) =>
|
||||||
|
_$PaginationDtoFromJson(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
@ -21,7 +45,8 @@ class HouseDataDto {
|
|||||||
|
|
||||||
const HouseDataDto(this.id, this.attributes);
|
const HouseDataDto(this.id, this.attributes);
|
||||||
|
|
||||||
factory HouseDataDto.fromJson(Map<String, dynamic> json) => _$HouseDataDtoFromJson(json);
|
factory HouseDataDto.fromJson(Map<String, dynamic> json) =>
|
||||||
|
_$HouseDataDtoFromJson(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
@ -31,7 +56,9 @@ class HouseAttributesDataDto {
|
|||||||
final String? image;
|
final String? image;
|
||||||
final String? description;
|
final String? description;
|
||||||
|
|
||||||
HouseAttributesDataDto(this.name, this.location, this.image, this.description);
|
HouseAttributesDataDto(
|
||||||
|
this.name, this.location, this.image, this.description);
|
||||||
|
|
||||||
factory HouseAttributesDataDto.fromJson(Map<String, dynamic> json) => _$HouseAttributesDataDtoFromJson(json);
|
factory HouseAttributesDataDto.fromJson(Map<String, dynamic> json) =>
|
||||||
|
_$HouseAttributesDataDtoFromJson(json);
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import '../dtos/houses_dto.dart';
|
import '../dtos/houses_dto.dart';
|
||||||
|
import 'package:pmd/models/home_data.dart';
|
||||||
import 'package:pmd/models/card_data.dart';
|
import 'package:pmd/models/card_data.dart';
|
||||||
|
|
||||||
extension HouseDataDtoToModel on HouseDataDto {
|
extension HouseDataDtoToModel on HouseDataDto {
|
||||||
@ -8,4 +9,10 @@ extension HouseDataDtoToModel on HouseDataDto {
|
|||||||
image: attributes?.image ?? "https://upload.wikimedia.org/wikipedia/commons/a/a2/Person_Image_Placeholder.png",
|
image: attributes?.image ?? "https://upload.wikimedia.org/wikipedia/commons/a/a2/Person_Image_Placeholder.png",
|
||||||
description: attributes?.description ?? "UNKNOWN"
|
description: attributes?.description ?? "UNKNOWN"
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
extension HousesDtoToModel on HousesDto {
|
||||||
|
HomeData toDomain() => HomeData(
|
||||||
|
data: data?.map((e) => e.toDomain()).toList(),
|
||||||
|
nextPage: meta?.pagination?.next);
|
||||||
}
|
}
|
7
lib/data/repositories/api_interface.dart
Normal file
7
lib/data/repositories/api_interface.dart
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import 'package:pmd/models/home_data.dart';
|
||||||
|
|
||||||
|
typedef OnErrorCallback = void Function(String? error);
|
||||||
|
|
||||||
|
abstract class ApiInterface {
|
||||||
|
Future<HomeData?> loadData ({OnErrorCallback? onError});
|
||||||
|
}
|
78
lib/data/repositories/mock_repository.dart
Normal file
78
lib/data/repositories/mock_repository.dart
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
import 'package:pmd/models/card_data.dart';
|
||||||
|
import 'package:pmd/data/repositories/api_interface.dart';
|
||||||
|
import 'package:pmd/models/home_data.dart';
|
||||||
|
|
||||||
|
class MockRepository extends ApiInterface {
|
||||||
|
// Список всех данных
|
||||||
|
final List<CardData> allData = [
|
||||||
|
const CardData(
|
||||||
|
name: "house 0",
|
||||||
|
image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
||||||
|
location: "Moscow",
|
||||||
|
description: "description null"),
|
||||||
|
const CardData(
|
||||||
|
name: "house 1",
|
||||||
|
image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
||||||
|
location: "Samara",
|
||||||
|
description: "null"),
|
||||||
|
const CardData(
|
||||||
|
name: "house 2",
|
||||||
|
image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
||||||
|
location: "Moscow",
|
||||||
|
description: "house good, very good"),
|
||||||
|
const CardData(
|
||||||
|
name: "house 3",
|
||||||
|
image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
||||||
|
location: "Kazan",
|
||||||
|
description: "house good"),
|
||||||
|
const CardData(
|
||||||
|
name: "house 4",
|
||||||
|
image: "https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
||||||
|
location: "Moscow",
|
||||||
|
description: "Moscow city")
|
||||||
|
];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<HomeData?> loadData({
|
||||||
|
String? q, // Поисковый запрос
|
||||||
|
int page = 1, // Страница по умолчанию
|
||||||
|
int pageSize = 2, // Количество элементов на странице
|
||||||
|
List<CardData>? currentData, // Текущие данные для динамического обновления
|
||||||
|
OnErrorCallback? onError,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
// Симуляция задержки сети для динамического обновления
|
||||||
|
await Future.delayed(const Duration(seconds: 1));
|
||||||
|
|
||||||
|
// Фильтрация данных по запросу, если он задан
|
||||||
|
List<CardData> filteredData = allData
|
||||||
|
.where((card) => q == null || card.name.toLowerCase().contains(q.toLowerCase()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
// Определяем начало и конец диапазона для пагинации
|
||||||
|
final int startIndex = (page - 1) * pageSize;
|
||||||
|
final int endIndex = startIndex + pageSize;
|
||||||
|
|
||||||
|
// Убедитесь, что индекс не выходит за пределы списка
|
||||||
|
if (startIndex >= filteredData.length) {
|
||||||
|
return HomeData(data: currentData ?? []); // Возвращаем текущие данные, если больше нет данных
|
||||||
|
}
|
||||||
|
|
||||||
|
// Извлекаем нужную страницу данных
|
||||||
|
List<CardData> paginatedData = filteredData.sublist(
|
||||||
|
startIndex,
|
||||||
|
endIndex > filteredData.length ? filteredData.length : endIndex,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Добавляем новые данные к текущим
|
||||||
|
if (currentData != null) {
|
||||||
|
paginatedData = [...currentData, ...paginatedData];
|
||||||
|
}
|
||||||
|
|
||||||
|
return HomeData(data: paginatedData);
|
||||||
|
} catch (e) {
|
||||||
|
if (onError != null) onError(e.toString());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -3,37 +3,44 @@ import 'dart:developer';
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:pmd/data/mapper/house_mapper.dart';
|
import 'package:pmd/data/mapper/house_mapper.dart';
|
||||||
import 'package:pmd/data/dtos/houses_dto.dart';
|
import 'package:pmd/data/dtos/houses_dto.dart';
|
||||||
import 'package:pmd/models/card_data.dart';
|
import 'package:pmd/models/home_data.dart';
|
||||||
import 'package:pmd/repositories/api_interface.dart';
|
import 'package:pmd/data/repositories/api_interface.dart';
|
||||||
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
|
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
|
||||||
|
|
||||||
|
|
||||||
class PotterRepository extends ApiInterface {
|
class PotterRepository extends ApiInterface {
|
||||||
static final Dio _dio = Dio(
|
static final Dio _dio = Dio(
|
||||||
BaseOptions(connectTimeout: Duration(seconds: 10)))
|
BaseOptions(connectTimeout: const Duration(seconds: 10)))
|
||||||
..interceptors.add(
|
..interceptors.add(
|
||||||
PrettyDioLogger(request: true, requestHeader: true, requestBody: true));
|
PrettyDioLogger(request: true, requestHeader: true, requestBody: true));
|
||||||
|
|
||||||
static const String _baseUrl = "https://api.potterdb.com/v1"; // https://api.realtor.com/v1
|
static const String _baseUrl =
|
||||||
|
"https://api.potterdb.com/v1"; // https://api.realtor.com/v1
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<List<CardData>?> loadData(String? q) async {
|
Future<HomeData?> loadData(
|
||||||
|
{OnErrorCallback? onError,
|
||||||
|
String? q,
|
||||||
|
int page = 1,
|
||||||
|
int pageSize = 10}) async {
|
||||||
try {
|
try {
|
||||||
const String url = '$_baseUrl/characters?page[size]=5';
|
const String url = '$_baseUrl/characters';
|
||||||
|
|
||||||
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
|
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
|
||||||
url,
|
url,
|
||||||
queryParameters: q != null ? {"filter[name_cont]": q} : null,
|
queryParameters: {
|
||||||
|
'filter[name_cont]': q,
|
||||||
|
'page[number]': page,
|
||||||
|
'page[size]': pageSize
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
final HousesDto dto =
|
final HousesDto dto =
|
||||||
HousesDto.fromJson(response.data as Map<String, dynamic>);
|
HousesDto.fromJson(response.data as Map<String, dynamic>);
|
||||||
|
|
||||||
final List<CardData>? data = dto.data?.map((e) => e.toDomain()).toList();
|
return dto.toDomain();
|
||||||
|
|
||||||
return data;
|
|
||||||
} on DioException catch (e) {
|
} on DioException catch (e) {
|
||||||
log("DioException: $e");
|
log("DioException: $e");
|
||||||
|
onError?.call(e.error?.toString());
|
||||||
return null;
|
return null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log('Unknown error: $e');
|
log('Unknown error: $e');
|
39
lib/home_page/bloc/bloc.dart
Normal file
39
lib/home_page/bloc/bloc.dart
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:pmd/data/repositories/mock_repository.dart';
|
||||||
|
import 'package:pmd/data/repositories/potter_repository.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/events.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/state.dart';
|
||||||
|
|
||||||
|
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
||||||
|
final PotterRepository repository;
|
||||||
|
|
||||||
|
// final MockRepository repository;
|
||||||
|
|
||||||
|
HomeBloc(this.repository) : 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 repository.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));
|
||||||
|
}
|
||||||
|
}
|
10
lib/home_page/bloc/events.dart
Normal file
10
lib/home_page/bloc/events.dart
Normal 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});
|
||||||
|
}
|
31
lib/home_page/bloc/state.dart
Normal file
31
lib/home_page/bloc/state.dart
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import 'package:equatable/equatable.dart';
|
||||||
|
import 'package:pmd/models/home_data.dart';
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Поля, по которым Equtable сравнивает состояния
|
||||||
|
@override
|
||||||
|
List<Object?> get props => [data, isLoading, isPaginationLoading, error];
|
||||||
|
}
|
@ -14,8 +14,7 @@ class _Card extends StatefulWidget {
|
|||||||
const _Card(
|
const _Card(
|
||||||
{required this.name, required this.location, required this.image, required this.description, required this.onLike, required this.onTap});
|
{required this.name, required this.location, required this.image, required this.description, required this.onLike, required this.onTap});
|
||||||
|
|
||||||
factory _Card.fromData(CardData data, OnLikeFunction? onLike,
|
factory _Card.fromData(CardData data, {OnLikeFunction? onLike, VoidCallback? onTap}) =>
|
||||||
VoidCallback? onTap) =>
|
|
||||||
_Card(
|
_Card(
|
||||||
name: data.name,
|
name: data.name,
|
||||||
location: data.location,
|
location: data.location,
|
||||||
|
@ -1,11 +1,16 @@
|
|||||||
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:pmd/utils/debounce.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/bloc.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/events.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/state.dart';
|
||||||
import 'package:pmd/models/card_data.dart';
|
import 'package:pmd/models/card_data.dart';
|
||||||
import 'package:pmd/details_page/details_page.dart';
|
import 'package:pmd/details_page/details_page.dart';
|
||||||
import 'package:pmd/repositories/api_interface.dart';
|
import 'package:pmd/data/repositories/api_interface.dart';
|
||||||
import 'package:pmd/repositories/mock_repository.dart';
|
|
||||||
|
|
||||||
import '../repositories/potter_repository.dart';
|
import 'package:pmd/data/repositories/mock_repository.dart';
|
||||||
|
import '../data/repositories/potter_repository.dart';
|
||||||
|
|
||||||
part 'card.dart';
|
part 'card.dart';
|
||||||
|
|
||||||
@ -20,14 +25,49 @@ class MyHomePage extends StatefulWidget {
|
|||||||
|
|
||||||
class _MyHomePageState extends State<MyHomePage> {
|
class _MyHomePageState extends State<MyHomePage> {
|
||||||
final TextEditingController _searchController = TextEditingController();
|
final TextEditingController _searchController = TextEditingController();
|
||||||
// final ApiInterface repository = PotterRepository();
|
final _scrollController = ScrollController();
|
||||||
final ApiInterface repository = MockRepository();
|
|
||||||
late Future<List<CardData>?> _data;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
context.read<HomeBloc>().add(const HomeLoadDataEvent());
|
||||||
|
});
|
||||||
|
|
||||||
|
_scrollController.addListener(_onNextPageListener);
|
||||||
super.initState();
|
super.initState();
|
||||||
_data = repository.loadData(null);
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_searchController.dispose();
|
||||||
|
_scrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onRefresh() {
|
||||||
|
context
|
||||||
|
.read<HomeBloc>()
|
||||||
|
.add(HomeLoadDataEvent(search: _searchController.text));
|
||||||
|
|
||||||
|
return Future.value(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSearchInputChange(search) {
|
||||||
|
Debounce.run(
|
||||||
|
action: () =>
|
||||||
|
context.read<HomeBloc>().add(HomeLoadDataEvent(search: search)));
|
||||||
}
|
}
|
||||||
|
|
||||||
void _showSnackBar(BuildContext context, String text) {
|
void _showSnackBar(BuildContext context, String text) {
|
||||||
@ -54,51 +94,62 @@ class _MyHomePageState extends State<MyHomePage> {
|
|||||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||||
title: Text(widget.title),
|
title: Text(widget.title),
|
||||||
),
|
),
|
||||||
body: ListView(
|
body: Column(
|
||||||
children: [
|
children: [
|
||||||
Column(
|
Padding(
|
||||||
children: [
|
padding:
|
||||||
Padding(
|
const EdgeInsets.only(right: 30, left: 30, top: 20, bottom: 20),
|
||||||
padding: const EdgeInsets.only(right: 30, left: 30, top: 20),
|
child: CupertinoSearchTextField(
|
||||||
child: CupertinoSearchTextField(
|
controller: _searchController,
|
||||||
controller: _searchController,
|
onChanged: _onSearchInputChange,
|
||||||
onChanged: (search) {
|
),
|
||||||
setState(() {
|
),
|
||||||
_data = repository.loadData(search);
|
BlocBuilder<HomeBloc, HomeState>(
|
||||||
});
|
builder: (context, state) => state.error != null
|
||||||
}),
|
? Text(
|
||||||
),
|
state.error ?? "",
|
||||||
FutureBuilder<List<CardData>?>(
|
style: Theme.of(context)
|
||||||
future: _data,
|
.textTheme
|
||||||
builder: (context, snapshot) => SingleChildScrollView(
|
.headlineSmall
|
||||||
padding: const EdgeInsets.symmetric(
|
?.copyWith(color: Colors.red),
|
||||||
horizontal: 30,
|
)
|
||||||
vertical: 15,
|
: state.isLoading
|
||||||
),
|
? const Padding(
|
||||||
child: snapshot.hasData
|
padding: EdgeInsets.only(top: 20),
|
||||||
? Column(
|
child: CircularProgressIndicator(),
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
)
|
||||||
children: snapshot.data?.map((cardData) {
|
: Expanded(
|
||||||
return Column(
|
child: RefreshIndicator(
|
||||||
children: [
|
onRefresh: _onRefresh,
|
||||||
const SizedBox(height: 20),
|
child: ListView.separated(
|
||||||
_Card.fromData(
|
controller: _scrollController,
|
||||||
cardData,
|
padding: const EdgeInsets.symmetric(
|
||||||
(String text) =>
|
vertical: 20, horizontal: 30),
|
||||||
|
separatorBuilder: (context, index) =>
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
itemCount: state.data?.data?.length ?? 0,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final data = state.data?.data?[index];
|
||||||
|
|
||||||
|
return data == null
|
||||||
|
? const SizedBox.shrink()
|
||||||
|
: _Card.fromData(
|
||||||
|
data,
|
||||||
|
onLike: (String text) =>
|
||||||
_showSnackBar(context, text),
|
_showSnackBar(context, text),
|
||||||
() => _navigateToDetailsPage(
|
onTap: () =>
|
||||||
context, cardData),
|
_navigateToDetailsPage(context, data),
|
||||||
),
|
);
|
||||||
const SizedBox(height: 20)
|
},
|
||||||
],
|
),
|
||||||
);
|
),
|
||||||
}).toList() ??
|
),
|
||||||
[])
|
),
|
||||||
: const CircularProgressIndicator(),
|
BlocBuilder<HomeBloc, HomeState>(
|
||||||
),
|
builder: (context, state) => state.isPaginationLoading
|
||||||
),
|
? const CircularProgressIndicator()
|
||||||
],
|
: const SizedBox.shrink(),
|
||||||
)
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
@ -1,4 +1,8 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:pmd/data/repositories/mock_repository.dart';
|
||||||
|
import 'package:pmd/data/repositories/potter_repository.dart';
|
||||||
|
import 'package:pmd/home_page/bloc/bloc.dart';
|
||||||
import 'package:pmd/home_page/home_page.dart';
|
import 'package:pmd/home_page/home_page.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@ -17,7 +21,15 @@ class MyApp extends StatelessWidget {
|
|||||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
||||||
useMaterial3: true,
|
useMaterial3: true,
|
||||||
),
|
),
|
||||||
home: const MyHomePage(title: 'Laboratory 5: API and Repositories.... '),
|
home: RepositoryProvider<PotterRepository>(
|
||||||
|
lazy: true,
|
||||||
|
create: (_) => PotterRepository(),
|
||||||
|
child: BlocProvider<HomeBloc>(
|
||||||
|
lazy: false,
|
||||||
|
create: (context) => HomeBloc(context.read<PotterRepository>()),
|
||||||
|
child: const MyHomePage(title: 'Laboratory 6: Architecture (Debounce and Bloc)'),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
8
lib/models/home_data.dart
Normal file
8
lib/models/home_data.dart
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import 'package:pmd/models/card_data.dart';
|
||||||
|
|
||||||
|
class HomeData {
|
||||||
|
final List<CardData>? data;
|
||||||
|
final int? nextPage;
|
||||||
|
|
||||||
|
HomeData({this.data, this.nextPage});
|
||||||
|
}
|
@ -1,5 +0,0 @@
|
|||||||
import 'package:pmd/models/card_data.dart';
|
|
||||||
|
|
||||||
abstract class ApiInterface {
|
|
||||||
Future<List<CardData>?> loadData (String? q);
|
|
||||||
}
|
|
@ -1,40 +0,0 @@
|
|||||||
import 'package:pmd/models/card_data.dart';
|
|
||||||
import 'package:pmd/repositories/api_interface.dart';
|
|
||||||
|
|
||||||
class MockRepository extends ApiInterface {
|
|
||||||
@override
|
|
||||||
Future<List<CardData>> loadData(String? q) async {
|
|
||||||
return [
|
|
||||||
CardData(
|
|
||||||
name: "house 0",
|
|
||||||
image:
|
|
||||||
"https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
|
||||||
location: "Moscow",
|
|
||||||
description: "description null"),
|
|
||||||
CardData(
|
|
||||||
name: "house 1",
|
|
||||||
image:
|
|
||||||
"https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
|
||||||
location: "Samara",
|
|
||||||
description: "null"),
|
|
||||||
CardData(
|
|
||||||
name: "house 2",
|
|
||||||
image:
|
|
||||||
"https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
|
||||||
location: "Moscow",
|
|
||||||
description: "house good, very good"),
|
|
||||||
CardData(
|
|
||||||
name: "house 3",
|
|
||||||
image:
|
|
||||||
"https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
|
||||||
location: "Kazan",
|
|
||||||
description: "house good"),
|
|
||||||
CardData(
|
|
||||||
name: "house 4",
|
|
||||||
image:
|
|
||||||
"https://cdn0.youla.io/files/images/780_780/63/29/6329d9f543eedb62b7695786-1.jpg",
|
|
||||||
location: "Moscow",
|
|
||||||
description: "Moscow city")
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
23
lib/utils/debounce.dart
Normal file
23
lib/utils/debounce.dart
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:ui';
|
||||||
|
|
||||||
|
class Debounce {
|
||||||
|
// Фабричный конструктор, возвращающий экзепляр класса Debounce. Паттерн Singleton
|
||||||
|
factory Debounce() => _instance;
|
||||||
|
|
||||||
|
// Приватный конструктор (Не даёт создание класса извне)
|
||||||
|
Debounce._();
|
||||||
|
|
||||||
|
// Статический экземпляр класса
|
||||||
|
static final Debounce _instance = Debounce._();
|
||||||
|
|
||||||
|
static Timer? _timer;
|
||||||
|
|
||||||
|
// Статический метод, где action функция, совершающая действие, а delay совершает задержку)
|
||||||
|
static void run(
|
||||||
|
{required VoidCallback action,
|
||||||
|
Duration delay = const Duration(milliseconds: 500)}) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = Timer(delay, action);
|
||||||
|
}
|
||||||
|
}
|
24
pubspec.lock
24
pubspec.lock
@ -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:
|
||||||
@ -198,6 +206,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 +243,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:
|
||||||
|
@ -43,6 +43,10 @@ dependencies:
|
|||||||
dio: ^5.4.2+1
|
dio: ^5.4.2+1
|
||||||
pretty_dio_logger: ^1.3.1
|
pretty_dio_logger: ^1.3.1
|
||||||
|
|
||||||
|
# Bloc (business logical component)
|
||||||
|
flutter_bloc: ^8.1.5
|
||||||
|
equatable: ^2.0.5
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
|
Loading…
Reference in New Issue
Block a user