поломала
This commit is contained in:
parent
61450b5ce5
commit
553442b492
21
lib/components/utils/debounce.dart
Normal file
21
lib/components/utils/debounce.dart
Normal file
@ -0,0 +1,21 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui';
|
||||
|
||||
class Debounce {
|
||||
factory Debounce() => _instance;
|
||||
|
||||
Debounce._();
|
||||
|
||||
static final Debounce _instance = Debounce._();
|
||||
|
||||
static Timer? _timer;
|
||||
|
||||
// Статический метод, после опред. задержки выполняется действие
|
||||
// если таймер уже был запущен, он отменяется
|
||||
static void run(
|
||||
{required VoidCallback action,
|
||||
Duration delay = const Duration(milliseconds: 500)}) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer(delay, action);
|
||||
}
|
||||
}
|
@ -5,19 +5,41 @@ part 'characters_dto.g.dart';
|
||||
@JsonSerializable(createToJson: false)
|
||||
class CharactersDto {
|
||||
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);
|
||||
}
|
||||
|
||||
@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)
|
||||
class CharacterDataDto {
|
||||
final String? id;
|
||||
final String? type;
|
||||
final CharacterAttributesDataDto? attributes; //составной элемент
|
||||
|
||||
const CharacterDataDto({this.id, this.type, this.attributes});
|
||||
const CharacterDataDto({this.id, this.attributes});
|
||||
|
||||
factory CharacterDataDto.fromJson(Map<String, dynamic> json) => _$CharacterDataDtoFromJson(json);
|
||||
}
|
||||
@ -25,11 +47,11 @@ class CharacterDataDto {
|
||||
@JsonSerializable(createToJson: false)
|
||||
class CharacterAttributesDataDto {
|
||||
final String? name;
|
||||
final String? born;
|
||||
final String? died;
|
||||
final String? image;
|
||||
final String? species;
|
||||
|
||||
const CharacterAttributesDataDto({this.name, this.born, this.died, this.image});
|
||||
CharacterAttributesDataDto(this.name, this.image, this.species);
|
||||
|
||||
factory CharacterAttributesDataDto.fromJson(Map<String, dynamic> json) => _$CharacterAttributesDataDtoFromJson(json);
|
||||
factory CharacterAttributesDataDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$CharacterAttributesDataDtoFromJson(json);
|
||||
}
|
@ -11,12 +11,27 @@ CharactersDto _$CharactersDtoFromJson(Map<String, dynamic> json) =>
|
||||
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>),
|
||||
);
|
||||
|
||||
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(),
|
||||
last: (json['last'] as num?)?.toInt(),
|
||||
next: (json['next'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) =>
|
||||
CharacterDataDto(
|
||||
id: json['id'] as String?,
|
||||
type: json['type'] as String?,
|
||||
attributes: json['attributes'] == null
|
||||
? null
|
||||
: CharacterAttributesDataDto.fromJson(
|
||||
@ -26,8 +41,7 @@ CharacterDataDto _$CharacterDataDtoFromJson(Map<String, dynamic> json) =>
|
||||
CharacterAttributesDataDto _$CharacterAttributesDataDtoFromJson(
|
||||
Map<String, dynamic> json) =>
|
||||
CharacterAttributesDataDto(
|
||||
name: json['name'] as String?,
|
||||
born: json['born'] as String?,
|
||||
died: json['died'] as String?,
|
||||
image: json['image'] as String?,
|
||||
json['name'] as String?,
|
||||
json['image'] as String?,
|
||||
json['species'] as String?,
|
||||
);
|
||||
|
@ -1,23 +1,17 @@
|
||||
import 'package:pmu/data/dtos/characters_dto.dart';
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
|
||||
const _imagePlaceholder =
|
||||
'https://upload.wikimedia.org/wikipedia/en/archive/b/b1/20210811082420%21Portrait_placeholder.png';
|
||||
import 'package:pmu/domain/models/home.dart';
|
||||
|
||||
extension CharacterDataDtoToModel on CharacterDataDto {
|
||||
CardData toDomain() => CardData(
|
||||
attributes?.name ?? 'UNKNOWN',
|
||||
imageUrl: attributes?.image ?? _imagePlaceholder,
|
||||
descriptionText: _makeDescriptionText(attributes?.born, attributes?.died),
|
||||
);
|
||||
|
||||
String _makeDescriptionText(String? born, String? died) {
|
||||
return born != null && died != null
|
||||
? '$born - $died'
|
||||
: born != null
|
||||
? 'born: $born'
|
||||
: died != null
|
||||
? 'died: $died'
|
||||
: '';
|
||||
}
|
||||
name: attributes?.name ?? "UNKNOWN",
|
||||
image: attributes?.image ??
|
||||
"https://upload.wikimedia.org/wikipedia/commons/a/a2/Person_Image_Placeholder.png",
|
||||
species: attributes?.species ?? "UNKNOWN");
|
||||
}
|
||||
|
||||
extension ChatactersDtoToModel on CharactersDto {
|
||||
HomeData toDomain() => HomeData(
|
||||
data: data?.map((e) => e.toDomain()).toList(),
|
||||
nextPage: meta?.pagination?.next);
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
import 'package:pmu/domain/models/home.dart';
|
||||
|
||||
typedef OnErrorCallback = void Function(String? error);
|
||||
|
||||
abstract class ApiInterface {
|
||||
Future<List<CardData>?> loadData({OnErrorCallback? onError});
|
||||
Future<HomeData?> loadData({OnErrorCallback? onError});
|
||||
}
|
@ -1,67 +1,22 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pmu/data/repositories/api_interface.dart';
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
import 'package:pmu/domain/models/home.dart';
|
||||
|
||||
class MockRepository extends ApiInterface {
|
||||
@override
|
||||
Future<List<CardData>?> loadData({OnErrorCallback? onError}) async {
|
||||
return [
|
||||
CardData(
|
||||
'собирается к первой паре',
|
||||
descriptionText: 'надел носочек и думает о смысле жизни',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/564x/7d/87/eb/7d87eb75ac6fcb46beabc5cb388c7d34.jpg',
|
||||
),
|
||||
CardData(
|
||||
'уснул за завтраком',
|
||||
descriptionText: 'всю ночь делал лабы....а кто не делал?',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/564x/c5/30/b6/c530b6de14c58fd8f56ec28dac9376c9.jpg',
|
||||
),
|
||||
CardData(
|
||||
'едет к первой паре',
|
||||
descriptionText: '(спит)',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/564x/b2/af/d9/b2afd919443c31d2d309a1c67b11930e.jpg',
|
||||
),
|
||||
CardData(
|
||||
'довольный',
|
||||
descriptionText: 'пришел в столовку строилки',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/736x/a3/12/0f/a3120feb082602247d5ab6d66bf2db61.jpg',
|
||||
),
|
||||
CardData(
|
||||
'делает лабы ночью',
|
||||
descriptionText: 'опять... ну ничему жизнь не учит',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://sun9-69.userapi.com/impg/MLc9nPmTUsLHA3Q53nqxz8tao0oyQ_5dGWidNQ/cXmzhWa97Qc.jpg?size=421x421&quality=95&sign=04c80f2ff2a43ff5b936190987e591e5&type=album',
|
||||
),
|
||||
CardData(
|
||||
'всё бросил и уехал в саратов',
|
||||
descriptionText: 'я ему завидую',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/564x/d4/25/fb/d425fb23ef181e36ad93d7c8c7f7292e.jpg',
|
||||
),
|
||||
CardData(
|
||||
'кушоет арбуз',
|
||||
descriptionText: 'и никакой депрессии!',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/736x/cc/e4/38/cce4384798b795b8d69e9caa8bf02c46.jpg',
|
||||
),
|
||||
CardData(
|
||||
'ой, а этот как сюда попал?',
|
||||
descriptionText: 'отвернитесь, он стесняется',
|
||||
icon: Icons.favorite,
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/736x/64/33/86/6433869ef972b167fb43cf74e0ad40aa.jpg',
|
||||
),
|
||||
];
|
||||
Future<HomeData?> loadData({OnErrorCallback? onError}) async {
|
||||
return HomeData(data: [
|
||||
const CardData(
|
||||
name: "test 0",
|
||||
species: "Species 0",
|
||||
image:
|
||||
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtAT11wKgHrJBUYzIBFogucXg0a9fE0fQXDQ&s"),
|
||||
const CardData(
|
||||
name: "test 1",
|
||||
species: "Species 1",
|
||||
image:
|
||||
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtAT11wKgHrJBUYzIBFogucXg0a9fE0fQXDQ&s")
|
||||
]);
|
||||
}
|
||||
}
|
@ -2,33 +2,46 @@ import 'package:dio/dio.dart';
|
||||
import 'package:pmu/data/dtos/characters_dto.dart';
|
||||
import 'package:pmu/data/mappers/characters_mapper.dart';
|
||||
import 'package:pmu/data/repositories/api_interface.dart';
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
|
||||
|
||||
class PotterRepository extends ApiInterface {
|
||||
static final Dio _dio = Dio()
|
||||
..interceptors.add(PrettyDioLogger(
|
||||
requestHeader: true,
|
||||
requestBody: true,
|
||||
));
|
||||
import 'dart:developer';
|
||||
import 'package:pmu/domain/models/home.dart';
|
||||
|
||||
static const String _baseUrl = 'https://api.potterdb.com';
|
||||
class PotterRepository extends ApiInterface {
|
||||
static final Dio _dio = Dio(
|
||||
BaseOptions(connectTimeout: const Duration(seconds: 10)))
|
||||
..interceptors.add(
|
||||
PrettyDioLogger(request: true, requestHeader: true, requestBody: true));
|
||||
|
||||
static const String _baseUrl = "https://api.potterdb.com/v1";
|
||||
|
||||
@override
|
||||
Future<List<CardData>?> loadData({String? q, OnErrorCallback? onError}) async {
|
||||
Future<HomeData?> loadData(
|
||||
{OnErrorCallback? onError,
|
||||
String? q,
|
||||
int page = 1,
|
||||
int pageSize = 10}) async {
|
||||
try {
|
||||
const String url = '$_baseUrl/v1/characters';
|
||||
const String url = '$_baseUrl/characters';
|
||||
|
||||
final Response<dynamic> response = await _dio.get<Map<dynamic, dynamic>>(
|
||||
url,
|
||||
queryParameters: q != null ? {'filter[name_cont]': q} : null,
|
||||
queryParameters: {
|
||||
'filter[name_cont]': q,
|
||||
'page[number]': page,
|
||||
'page[size]': pageSize
|
||||
},
|
||||
);
|
||||
|
||||
final CharactersDto dto = CharactersDto.fromJson(response.data as Map<String, dynamic>);
|
||||
final List<CardData>? data = dto.data?.map((e) => e.toDomain()).toList();
|
||||
return data;
|
||||
final CharactersDto dto =
|
||||
CharactersDto.fromJson(response.data as Map<String, dynamic>);
|
||||
return dto.toDomain();
|
||||
} on DioException catch (e) {
|
||||
onError?.call(e.response?.statusMessage);
|
||||
log("DioException: $e");
|
||||
onError?.call(e.error?.toString());
|
||||
return null;
|
||||
} catch (e) {
|
||||
log('Unknown error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class CardData {
|
||||
final String text;
|
||||
final String descriptionText;
|
||||
final IconData icon;
|
||||
final String? imageUrl;
|
||||
final String name;
|
||||
final String image;
|
||||
final String species;
|
||||
|
||||
CardData(
|
||||
this.text, {
|
||||
required this.descriptionText,
|
||||
this.icon = Icons.catching_pokemon,
|
||||
this.imageUrl,
|
||||
});
|
||||
const CardData({required this.name, required this.image, required this.species});
|
||||
}
|
8
lib/domain/models/home.dart
Normal file
8
lib/domain/models/home.dart
Normal file
@ -0,0 +1,8 @@
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
|
||||
class HomeData {
|
||||
final List<CardData>? data;
|
||||
final int? nextPage;
|
||||
|
||||
HomeData({this.data, this.nextPage});
|
||||
}
|
@ -1,5 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pmu/presentation/home_page/home_page.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:pmu/data/repositories/mock_repository.dart';
|
||||
import 'package:pmu/data/repositories/potter_repository.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/bloc.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const MyApp());
|
||||
@ -14,10 +18,18 @@ class MyApp extends StatelessWidget {
|
||||
title: 'Flutter Demo',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.orange),
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.brown.shade300),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: const MyHomePage(title: 'Сафиулова Камилия Наилевна'),
|
||||
home: RepositoryProvider<PotterRepository>(
|
||||
lazy: true,
|
||||
create: (_) => PotterRepository(),
|
||||
child: BlocProvider<HomeBloc>(
|
||||
lazy: false,
|
||||
create: (context) => HomeBloc(context.read<PotterRepository>()),
|
||||
child: const MyHomePage(title: 'Сафиулова Камилия Наилевна'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -5,45 +5,39 @@ import 'package:pmu/domain/models/card.dart';
|
||||
class DetailsPage extends StatelessWidget {
|
||||
final CardData data;
|
||||
|
||||
const DetailsPage(this.data, {super.key});
|
||||
const DetailsPage({super.key, required this.data});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0), // Добавляем общий отступ слева и справа
|
||||
appBar: AppBar(
|
||||
title: Text('Character ${data.name}'),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(30),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16.0),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
Center(
|
||||
child: Image.network(
|
||||
data.imageUrl ?? '',
|
||||
fit: BoxFit.cover,
|
||||
width: double.infinity,
|
||||
height: 400.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4.0),
|
||||
child: Text(
|
||||
data.text,
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
data.image,
|
||||
width: 250,
|
||||
height: 250,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
data.descriptionText,
|
||||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
|
||||
fontSize: 25.0,
|
||||
data.name,
|
||||
style: const TextStyle(fontSize: 18),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
"Species: ${data.species}",
|
||||
style: const TextStyle(fontSize: 25, color: Colors.orange),
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
37
lib/presentation/home_page/bloc/bloc.dart
Normal file
37
lib/presentation/home_page/bloc/bloc.dart
Normal file
@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:pmu/data/repositories/mock_repository.dart';
|
||||
import 'package:pmu/data/repositories/potter_repository.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/events.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/state.dart';
|
||||
|
||||
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
||||
final PotterRepository 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/presentation/home_page/bloc/events.dart
Normal file
10
lib/presentation/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});
|
||||
}
|
35
lib/presentation/home_page/bloc/state.dart
Normal file
35
lib/presentation/home_page/bloc/state.dart
Normal file
@ -0,0 +1,35 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:pmu/domain/models/home.dart';
|
||||
|
||||
part 'state.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class HomeState extends Equatable { //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];
|
||||
}
|
@ -1,18 +1,19 @@
|
||||
part of 'home_page.dart';
|
||||
part of "home_page.dart";
|
||||
|
||||
typedef OnLikeCallback = void Function(String title, bool isLiked)?;
|
||||
typedef OnLikeFunction = void Function(String text);
|
||||
|
||||
class _Card extends StatefulWidget {
|
||||
final String text;
|
||||
final String descriptionText;
|
||||
final IconData icon;
|
||||
final String? imageUrl;
|
||||
final OnLikeCallback onLike;
|
||||
|
||||
final OnLikeFunction? onLike;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
const _Card(
|
||||
this.text, {
|
||||
this.icon = Icons.catching_pokemon,
|
||||
this.icon = Icons.ac_unit_outlined,
|
||||
required this.descriptionText,
|
||||
this.imageUrl,
|
||||
this.onLike,
|
||||
@ -40,17 +41,25 @@ class _Card extends StatefulWidget {
|
||||
class _CardState extends State<_Card> {
|
||||
bool isLiked = false;
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(16),
|
||||
constraints: const BoxConstraints(minHeight: 140),
|
||||
constraints: const BoxConstraints(minHeight: 160),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white70,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: Colors.grey.shade200),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.grey.withOpacity(.5),
|
||||
spreadRadius: 4,
|
||||
offset: const Offset(0, 5),
|
||||
blurRadius: 8,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: IntrinsicHeight(
|
||||
child: Row(
|
||||
@ -63,14 +72,16 @@ class _CardState extends State<_Card> {
|
||||
),
|
||||
child: SizedBox(
|
||||
height: double.infinity,
|
||||
width: 160,
|
||||
width: 120,
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: Image.network(
|
||||
widget.imageUrl ?? '',
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => const Placeholder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 16.0),
|
||||
@ -79,12 +90,12 @@ class _CardState extends State<_Card> {
|
||||
children: [
|
||||
Text(
|
||||
widget.text,
|
||||
style: Theme.of(context).textTheme.headlineLarge,
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
Text(
|
||||
widget.descriptionText,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
@ -93,19 +104,17 @@ class _CardState extends State<_Card> {
|
||||
alignment: Alignment.bottomRight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
left: 8.0,
|
||||
right: 16.0,
|
||||
bottom: 16.0,
|
||||
left: 8,
|
||||
right: 16,
|
||||
bottom: 16,
|
||||
),
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
setState(() {
|
||||
isLiked = !isLiked;
|
||||
});
|
||||
setState(() => isLiked = !isLiked);
|
||||
widget.onLike?.call(widget.text, isLiked);
|
||||
},
|
||||
child: AnimatedSwitcher(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: isLiked
|
||||
? const Icon(
|
||||
Icons.favorite,
|
||||
|
@ -1,9 +1,13 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pmu/domain/models/card.dart';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:pmu/components/utils/debounce.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/bloc.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/events.dart';
|
||||
import 'package:pmu/presentation/home_page/bloc/state.dart';
|
||||
import '../details_page/details_page.dart';
|
||||
import 'package:pmu/data/repositories/potter_repository.dart';
|
||||
|
||||
part 'card.dart';
|
||||
|
||||
class MyHomePage extends StatefulWidget {
|
||||
@ -16,94 +20,134 @@ class MyHomePage extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _MyHomePageState extends State<MyHomePage> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Scaffold(body: Body());
|
||||
}
|
||||
}
|
||||
|
||||
class Body extends StatefulWidget {
|
||||
const Body({super.key});
|
||||
|
||||
@override
|
||||
State<Body> createState() => _BodyState();
|
||||
}
|
||||
|
||||
class _BodyState extends State<Body> {
|
||||
final searchController = TextEditingController();
|
||||
late Future<List<CardData>?> data;
|
||||
|
||||
final repo = PotterRepository();
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
final _scrollController = ScrollController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
data = repo.loadData();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
context.read<HomeBloc>().add(const HomeLoadDataEvent());
|
||||
});
|
||||
|
||||
_scrollController.addListener(_onNextPageListener);
|
||||
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@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) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(text),
|
||||
duration: const Duration(seconds: 2),
|
||||
backgroundColor: Colors.black54,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
void _navigateToDetailsPage(BuildContext context, CardData data) {
|
||||
Navigator.push(
|
||||
context,
|
||||
CupertinoPageRoute(builder: (context) => DetailsPage(data: data)),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
|
||||
child: Column(
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
|
||||
title: Text(widget.title),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
padding:
|
||||
const EdgeInsets.only(right: 30, left: 30, top: 20, bottom: 20),
|
||||
child: CupertinoSearchTextField(
|
||||
controller: searchController,
|
||||
onChanged: (search) {
|
||||
setState(() {
|
||||
data = repo.loadData(q: search);
|
||||
});
|
||||
controller: _searchController,
|
||||
onChanged: _onSearchInputChange,
|
||||
),
|
||||
),
|
||||
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 Padding(
|
||||
padding: EdgeInsets.only(top: 20),
|
||||
child: CircularProgressIndicator(),
|
||||
)
|
||||
: Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: _onRefresh,
|
||||
child: ListView.separated(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
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),
|
||||
onTap: () =>
|
||||
_navigateToDetailsPage(context, data),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
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() ??
|
||||
[],
|
||||
)
|
||||
: const CircularProgressIndicator(),
|
||||
),
|
||||
),
|
||||
),
|
||||
BlocBuilder<HomeBloc, HomeState>(
|
||||
builder: (context, state) => state.isPaginationLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _navToDetails(BuildContext context, CardData data) {
|
||||
Navigator.push(
|
||||
context,
|
||||
CupertinoPageRoute(builder: (context) => DetailsPage(data)),
|
||||
);
|
||||
}
|
||||
|
||||
void _showSnackBar(BuildContext context, String title, bool isLiked) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(
|
||||
'$title ${isLiked ? 'liked!' : 'disliked :('}',
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
backgroundColor: Colors.brown.shade300,
|
||||
duration: const Duration(seconds: 1),
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
56
pubspec.lock
56
pubspec.lock
@ -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:
|
||||
@ -198,6 +222,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:
|
||||
@ -227,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:
|
||||
@ -392,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:
|
||||
@ -424,6 +472,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:
|
||||
|
@ -33,6 +33,12 @@ dependencies:
|
||||
json_annotation: ^4.8.1
|
||||
dio: ^5.4.2+1
|
||||
pretty_dio_logger: ^1.3.1
|
||||
copy_with_extension_gen: ^5.0.4
|
||||
|
||||
# Bloc (business logical component)
|
||||
equatable: ^2.0.5
|
||||
flutter_bloc: ^8.1.5
|
||||
|
||||
|
||||
# The following adds the Cupertino Icons font to your application.
|
||||
# Use with the CupertinoIcons class for iOS style icons.
|
||||
|
Loading…
Reference in New Issue
Block a user