базово 6 лаба готова
This commit is contained in:
parent
192c7f6472
commit
604a39379e
19
lib/components/utils/debounce.dart
Normal file
19
lib/components/utils/debounce.dart
Normal file
@ -0,0 +1,19 @@
|
||||
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: 700),
|
||||
}) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer(delay, action);
|
||||
}
|
||||
}
|
@ -5,23 +5,48 @@ part 'spells_dto.g.dart';
|
||||
@JsonSerializable(createToJson: false)
|
||||
class SpellsDto {
|
||||
final List<SpellDataDto>? data;
|
||||
final MetaDto? meta;
|
||||
|
||||
const SpellsDto({
|
||||
this.data,
|
||||
this.meta,
|
||||
});
|
||||
|
||||
factory SpellsDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$SpellDtoFromJson(json);
|
||||
_$SpellsDtoFromJson(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;
|
||||
final int? records;
|
||||
|
||||
const PaginationDto({this.current, this.next, this.last, this.records});
|
||||
|
||||
factory PaginationDto.fromJson(Map<String, dynamic> json) =>
|
||||
_$PaginationDtoFromJson(json);
|
||||
}
|
||||
|
||||
@JsonSerializable(createToJson: false)
|
||||
class SpellDataDto {
|
||||
final String? id;
|
||||
final String id;
|
||||
final String? type;
|
||||
final SpellAttributesDataDto? attributes;
|
||||
|
||||
const SpellDataDto({
|
||||
this.id,
|
||||
const SpellDataDto(
|
||||
this.id, {
|
||||
this.type,
|
||||
this.attributes,
|
||||
});
|
||||
|
@ -6,14 +6,31 @@ part of 'spells_dto.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
SpellsDto _$SpellDtoFromJson(Map<String, dynamic> json) => SpellsDto(
|
||||
SpellsDto _$SpellsDtoFromJson(Map<String, dynamic> json) => SpellsDto(
|
||||
data: (json['data'] as List<dynamic>?)
|
||||
?.map((e) => SpellDataDto.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
meta: json['meta'] == null
|
||||
? null
|
||||
: MetaDto.fromJson(json['meta'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
MetaDto _$MetaDtoFromJson(Map<String, dynamic> json) => MetaDto(
|
||||
pagination: json['pagination'] == null
|
||||
? null
|
||||
: PaginationDto.fromJson(json['pagination'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
PaginationDto _$PaginationDtoFromJson(Map<String, dynamic> json) =>
|
||||
PaginationDto(
|
||||
current: (json['current'] as num?)?.toInt(),
|
||||
next: (json['next'] as num?)?.toInt(),
|
||||
last: (json['last'] as num?)?.toInt(),
|
||||
records: (json['records'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
SpellDataDto _$SpellDataDtoFromJson(Map<String, dynamic> json) => SpellDataDto(
|
||||
id: json['id'] as String?,
|
||||
json['id'] as String,
|
||||
type: json['type'] as String?,
|
||||
attributes: json['attributes'] == null
|
||||
? null
|
||||
|
@ -1,11 +1,20 @@
|
||||
import 'package:laba1/domain/models/card.dart';
|
||||
|
||||
import '../../domain/models/home.dart';
|
||||
import '../dtos/spells_dto.dart';
|
||||
|
||||
const _imagePlaceHolder ='https://cdn-icons-png.flaticon.com/512/1277/1277244.png';
|
||||
|
||||
extension SpellsDtoToModel on SpellsDto {
|
||||
HomeData toDomain() => HomeData(
|
||||
data: data?.map((e) => e.toDomain()).toList(),
|
||||
nextPage: meta?.pagination?.next,
|
||||
);
|
||||
}
|
||||
|
||||
extension SpellsDataDtoToModel on SpellDataDto {
|
||||
CardData toDomain() => CardData(
|
||||
id,
|
||||
attributes?.name ?? 'UNKNOWN',
|
||||
imageUrl: attributes?.image ?? _imagePlaceHolder,
|
||||
description: _makeDescription(attributes),
|
||||
|
@ -1,7 +1,8 @@
|
||||
import '../../domain/models/card.dart';
|
||||
import '../../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,25 +1,28 @@
|
||||
import '../../domain/models/card.dart';
|
||||
import '../../domain/models/home.dart';
|
||||
import 'api_interface.dart';
|
||||
|
||||
class MockRepository extends ApiInterface {
|
||||
@override
|
||||
Future<List<CardData>?> loadData({OnErrorCallback? onError}) async {
|
||||
return [
|
||||
CardData('orange',
|
||||
imageUrl:
|
||||
'https://kuban24.tv/wp-content/uploads/2023/10/photo_2023-10-02_16-08-02.jpg'),
|
||||
CardData("aboba",
|
||||
imageUrl:
|
||||
'https://masterpiecer-images.s3.yandex.net/5fa453a2d4c51a7:upscaled'),
|
||||
CardData("Hello world!!!",
|
||||
imageUrl:
|
||||
'https://m.media-amazon.com/images/I/81YqUbAZ0GL._AC_UF1000,1000_QL80_.jpg'),
|
||||
CardData('(=^・^=)',
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/236x/c8/cc/24/c8cc24bba37a25c009647b8875aae0e3.jpg'),
|
||||
CardData('плохо быть старым ' + 'трезвым и больным, ' * 5,
|
||||
imageUrl:
|
||||
'https://images.genius.com/c754c6f1755acee741881d55985a6c34.865x865x1.jpg'),
|
||||
];
|
||||
Future<HomeData?> loadData({OnErrorCallback? onError}) async {
|
||||
return HomeData(
|
||||
data: [
|
||||
CardData('a', 'orange',
|
||||
imageUrl:
|
||||
'https://kuban24.tv/wp-content/uploads/2023/10/photo_2023-10-02_16-08-02.jpg'),
|
||||
CardData('b', "aboba",
|
||||
imageUrl:
|
||||
'https://masterpiecer-images.s3.yandex.net/5fa453a2d4c51a7:upscaled'),
|
||||
CardData('c', "Hello world!!!",
|
||||
imageUrl:
|
||||
'https://m.media-amazon.com/images/I/81YqUbAZ0GL._AC_UF1000,1000_QL80_.jpg'),
|
||||
CardData('d', '(=^・^=)',
|
||||
imageUrl:
|
||||
'https://i.pinimg.com/236x/c8/cc/24/c8cc24bba37a25c009647b8875aae0e3.jpg'),
|
||||
CardData('e', 'плохо быть старым ' + 'трезвым и больным, ' * 5,
|
||||
imageUrl:
|
||||
'https://images.genius.com/c754c6f1755acee741881d55985a6c34.865x865x1.jpg'),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ import 'package:laba1/data/mappers/spells_mapper.dart';
|
||||
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
|
||||
|
||||
import '../../domain/models/card.dart';
|
||||
import '../../domain/models/home.dart';
|
||||
import '../dtos/spells_dto.dart';
|
||||
import 'api_interface.dart';
|
||||
|
||||
@ -16,49 +17,55 @@ class PotterRepository extends ApiInterface {
|
||||
static const String _baseUrl = 'https://api.potterdb.com';
|
||||
|
||||
@override
|
||||
Future<List<CardData>?> loadData(
|
||||
{String? q, OnErrorCallback? onError}) async {
|
||||
Future<HomeData?> loadData({
|
||||
OnErrorCallback? onError,
|
||||
String? q,
|
||||
int page = 1,
|
||||
int pageSize = 25,
|
||||
}) async {
|
||||
try {
|
||||
const String url = '$_baseUrl/v1/spells';
|
||||
|
||||
SpellsDto dto;
|
||||
if (q == null) {
|
||||
final Response<dynamic> response =
|
||||
await _dio.get<Map<dynamic, dynamic>>(url);
|
||||
await _dio.get<Map<dynamic, dynamic>>(url, queryParameters: {
|
||||
'filter[name_cont]': q,
|
||||
'page[number]': page,
|
||||
'page[size]': pageSize,
|
||||
});
|
||||
dto = SpellsDto.fromJson(response.data as Map<String, dynamic>);
|
||||
} else {
|
||||
final Response<dynamic> response1 =
|
||||
await _dio.get<Map<dynamic, dynamic>>(
|
||||
url,
|
||||
queryParameters: q != null ? {'filter[name_cont]': q} : null,
|
||||
);
|
||||
final Response<dynamic> response2 =
|
||||
await _dio.get<Map<dynamic, dynamic>>(
|
||||
url,
|
||||
queryParameters: q != null ? {'filter[incantation_cont]': q} : null,
|
||||
);
|
||||
SpellsDto dto1 =
|
||||
SpellsDto.fromJson(response1.data as Map<String, dynamic>);
|
||||
SpellsDto dto2 =
|
||||
SpellsDto.fromJson(response2.data as Map<String, dynamic>);
|
||||
|
||||
List<SpellDataDto> combinedData = [
|
||||
...?dto1.data, // добавляем данные из dto1
|
||||
...?dto2.data // добавляем данные из dto2
|
||||
];
|
||||
// Удаляем дубликаты по полю id
|
||||
Map<String?, SpellDataDto> uniqueSpellsMap = {
|
||||
for (var spell in combinedData) spell.id: spell
|
||||
};
|
||||
// Преобразуем обратно в список
|
||||
List<SpellDataDto> uniqueSpells = uniqueSpellsMap.values.toList();
|
||||
// Создаем новый SpellsDto с уникальными данными
|
||||
dto = SpellsDto(data: uniqueSpells);
|
||||
return dto.toDomain();
|
||||
}
|
||||
final List<CardData>? data = dto.data?.map((e) => e.toDomain()).toList();
|
||||
return data;
|
||||
|
||||
final Response<dynamic> response1 =
|
||||
await _dio.get<Map<dynamic, dynamic>>(url, queryParameters: {
|
||||
'filter[name_cont]': q,
|
||||
'page[number]': page,
|
||||
'page[size]': pageSize,
|
||||
});
|
||||
SpellsDto dto1 =
|
||||
SpellsDto.fromJson(response1.data as Map<String, dynamic>);
|
||||
|
||||
final HomeData homeData1 = dto1.toDomain();
|
||||
if (homeData1.data != null && homeData1.data!.isNotEmpty)
|
||||
return HomeData(data: homeData1.data, nextPage: page+1);
|
||||
|
||||
page -= ((dto1.meta?.pagination?.records ?? 0) / pageSize).ceil();
|
||||
|
||||
final Response<dynamic> response2 =
|
||||
await _dio.get<Map<dynamic, dynamic>>(url, queryParameters: {
|
||||
'filter[incantation_cont]': q,
|
||||
'page[number]': page,
|
||||
'page[size]': pageSize,
|
||||
});
|
||||
SpellsDto dto2 =
|
||||
SpellsDto.fromJson(response2.data as Map<String, dynamic>);
|
||||
|
||||
return dto2.toDomain();
|
||||
|
||||
} on DioException catch (e) {
|
||||
onError?.call(e.response?.statusMessage);
|
||||
onError?.call(e.error?.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,11 @@
|
||||
class CardData {
|
||||
final String id;
|
||||
final String text;
|
||||
final String? description;
|
||||
final String? imageUrl;
|
||||
|
||||
CardData(
|
||||
this.id,
|
||||
this.text, {
|
||||
this.description,
|
||||
this.imageUrl,
|
||||
|
13
lib/domain/models/home.dart
Normal file
13
lib/domain/models/home.dart
Normal file
@ -0,0 +1,13 @@
|
||||
import 'card.dart';
|
||||
|
||||
class HomeData {
|
||||
final List<CardData>? data;
|
||||
final Set<String> existingIds = <String>{};
|
||||
int? nextPage;
|
||||
|
||||
HomeData({this.data, this.nextPage}) {
|
||||
for (var entity in data ?? []) {
|
||||
existingIds.add(entity.id);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:laba1/data/repositories/mock_repository.dart';
|
||||
import 'package:laba1/presentation/home_page/bloc/state.dart';
|
||||
|
||||
import '../../../data/repositories/potter_repository.dart';
|
||||
@ -7,10 +6,51 @@ import 'events.dart';
|
||||
|
||||
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
||||
final PotterRepository repo;
|
||||
|
||||
HomeBloc(this.repo) : super(const HomeState()) {
|
||||
on<HomeLoadDataEvent>(_onLoadData);
|
||||
}
|
||||
void _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) {
|
||||
emit(state.copyWith(data: repo.loadData()));
|
||||
|
||||
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,
|
||||
);
|
||||
data?.nextPage = data?.nextPage ?? (event.nextPage ?? 1);
|
||||
if (event.nextPage != null) {
|
||||
// Добавляем новые данные, пропуская дубликаты
|
||||
if (state.data != null) {
|
||||
for (var entity in data?.data ?? []) {
|
||||
if (!(state.data!.existingIds.contains(entity.id))) {
|
||||
state.data?.data?.add(entity);
|
||||
state.data?.existingIds.add(entity.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
state.data?.nextPage = data?.nextPage;
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
isPaginationLoading: false,
|
||||
data: state.data,
|
||||
error: error,
|
||||
));
|
||||
} else {
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
isPaginationLoading: false,
|
||||
data: data,
|
||||
error: error,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,10 @@
|
||||
abstract class HomeEvent {
|
||||
const HomeEvent();
|
||||
}
|
||||
|
||||
class HomeLoadDataEvent extends HomeEvent {
|
||||
const HomeLoadDataEvent();
|
||||
}
|
||||
final String? search;
|
||||
final int? nextPage;
|
||||
|
||||
const HomeLoadDataEvent({this.search, this.nextPage});
|
||||
}
|
||||
|
@ -1,11 +1,30 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../../../domain/models/card.dart';
|
||||
import '../../../domain/models/home.dart';
|
||||
|
||||
part 'state.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class HomeState extends Equatable {
|
||||
final Future<List<CardData>?>? data;
|
||||
const HomeState({this.data});
|
||||
HomeState copyWith({Future<List<CardData>?>? data}) => HomeState(data: data ?? this.data);
|
||||
final HomeData? data;
|
||||
final bool isLoading;
|
||||
final bool isPaginationLoading;
|
||||
final String? error;
|
||||
|
||||
const HomeState({
|
||||
this.data,
|
||||
this.isLoading = false,
|
||||
this.isPaginationLoading = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [data];
|
||||
}
|
||||
List<Object?> get props => [
|
||||
data,
|
||||
isLoading,
|
||||
isPaginationLoading,
|
||||
error,
|
||||
];
|
||||
}
|
||||
|
92
lib/presentation/home_page/bloc/state.g.dart
Normal file
92
lib/presentation/home_page/bloc/state.g.dart
Normal file
@ -0,0 +1,92 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$HomeStateCWProxy {
|
||||
HomeState data(HomeData? data);
|
||||
|
||||
HomeState isLoading(bool isLoading);
|
||||
|
||||
HomeState isPaginationLoading(bool isPaginationLoading);
|
||||
|
||||
HomeState error(String? error);
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `HomeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// HomeState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
HomeState call({
|
||||
HomeData? data,
|
||||
bool? isLoading,
|
||||
bool? isPaginationLoading,
|
||||
String? error,
|
||||
});
|
||||
}
|
||||
|
||||
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfHomeState.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfHomeState.copyWith.fieldName(...)`
|
||||
class _$HomeStateCWProxyImpl implements _$HomeStateCWProxy {
|
||||
const _$HomeStateCWProxyImpl(this._value);
|
||||
|
||||
final HomeState _value;
|
||||
|
||||
@override
|
||||
HomeState data(HomeData? data) => this(data: data);
|
||||
|
||||
@override
|
||||
HomeState isLoading(bool isLoading) => this(isLoading: isLoading);
|
||||
|
||||
@override
|
||||
HomeState isPaginationLoading(bool isPaginationLoading) =>
|
||||
this(isPaginationLoading: isPaginationLoading);
|
||||
|
||||
@override
|
||||
HomeState error(String? error) => this(error: error);
|
||||
|
||||
@override
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `HomeState(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// HomeState(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
HomeState call({
|
||||
Object? data = const $CopyWithPlaceholder(),
|
||||
Object? isLoading = const $CopyWithPlaceholder(),
|
||||
Object? isPaginationLoading = const $CopyWithPlaceholder(),
|
||||
Object? error = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return HomeState(
|
||||
data: data == const $CopyWithPlaceholder()
|
||||
? _value.data
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: data as HomeData?,
|
||||
isLoading: isLoading == const $CopyWithPlaceholder() || isLoading == null
|
||||
? _value.isLoading
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: isLoading as bool,
|
||||
isPaginationLoading:
|
||||
isPaginationLoading == const $CopyWithPlaceholder() ||
|
||||
isPaginationLoading == null
|
||||
? _value.isPaginationLoading
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: isPaginationLoading as bool,
|
||||
error: error == const $CopyWithPlaceholder()
|
||||
? _value.error
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: error as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $HomeStateCopyWith on HomeState {
|
||||
/// Returns a callable class that can be used as follows: `instanceOfHomeState.copyWith(...)` or like so:`instanceOfHomeState.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$HomeStateCWProxy get copyWith => _$HomeStateCWProxyImpl(this);
|
||||
}
|
@ -4,6 +4,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:laba1/data/repositories/potter_repository.dart';
|
||||
import 'package:laba1/presentation/details_page/details_page.dart';
|
||||
|
||||
import '../../components/utils/debounce.dart';
|
||||
import '../../data/repositories/mock_repository.dart';
|
||||
import '../../domain/models/card.dart';
|
||||
import '../dialogs/show_dialog.dart';
|
||||
@ -44,88 +45,110 @@ class _Body extends StatefulWidget {
|
||||
|
||||
class _BodyState extends State<_Body> {
|
||||
final searchController = TextEditingController();
|
||||
final scrollController = ScrollController();
|
||||
|
||||
@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) {
|
||||
// preventing multiple pagination request on multiple swipes
|
||||
final bloc = context.read<HomeBloc>();
|
||||
if (!bloc.state.isPaginationLoading) {
|
||||
bloc.add(HomeLoadDataEvent(
|
||||
search: searchController.text,
|
||||
nextPage: bloc.state.data?.nextPage,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
searchController.dispose();
|
||||
scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Stack(
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
|
||||
child: Column(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: BlocBuilder<HomeBloc, HomeState > (
|
||||
builder: (context, state) =>
|
||||
FutureBuilder<List<CardData>?>(
|
||||
future: state.data,
|
||||
builder: (context, snapshot) {
|
||||
var cards = Column(
|
||||
children: [],
|
||||
);
|
||||
cards.children.add(Padding(
|
||||
padding: const EdgeInsets.only(left: 8.0, right: 8),
|
||||
child: CupertinoSearchTextField(
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomLeft: Radius.circular(20),
|
||||
bottomRight: Radius.circular(20),
|
||||
),
|
||||
backgroundColor: Colors.amberAccent,
|
||||
),
|
||||
));
|
||||
cards.children.addAll(
|
||||
snapshot.data
|
||||
?.map((e) =>
|
||||
_Card.fromData(
|
||||
e,
|
||||
onLike: (String title, bool isLiked) {
|
||||
_showSnackBar(context, title, isLiked);
|
||||
},
|
||||
onTap: () => _navToDetails(context, e),
|
||||
))
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
return snapshot.hasData
|
||||
? SingleChildScrollView(
|
||||
child: cards,
|
||||
)
|
||||
: Center(child: CircularProgressIndicator());
|
||||
},
|
||||
),
|
||||
),),
|
||||
Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 8.0, right: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: CupertinoSearchTextField(
|
||||
borderRadius: BorderRadius.only(
|
||||
bottomLeft: Radius.circular(20),
|
||||
bottomRight: Radius.circular(20),
|
||||
),
|
||||
backgroundColor: Colors.amberAccent,
|
||||
controller: searchController,
|
||||
onChanged: (search) {
|
||||
//TODO
|
||||
Debounce.run(() => context
|
||||
.read<HomeBloc>()
|
||||
.add(HomeLoadDataEvent(search: search)));
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
BlocBuilder<HomeBloc, HomeState>(
|
||||
builder: (context, state) => state.error != null
|
||||
? Text(
|
||||
state.error ?? '',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineSmall
|
||||
?.copyWith(color: Colors.red),
|
||||
)
|
||||
: state.isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: _onRefresh,
|
||||
child: ListView.builder(
|
||||
controller: scrollController,
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: (state.data?.data?.length ?? 0) + 1,
|
||||
itemBuilder: (context, index) {
|
||||
if (index == 0) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: CupertinoSearchTextField(),
|
||||
);
|
||||
}
|
||||
final data = state.data?.data?[index-1];
|
||||
return data != null
|
||||
? _Card.fromData(
|
||||
data,
|
||||
onLike: (title, isLiked) => _showSnackBar(
|
||||
context, title, isLiked),
|
||||
onTap: () => _navToDetails(context, data),
|
||||
)
|
||||
: const SizedBox.expand();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
BlocBuilder<HomeBloc, HomeState>(
|
||||
builder: (context, state) => state.isPaginationLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onRefresh() {
|
||||
context
|
||||
.read<HomeBloc>()
|
||||
.add(HomeLoadDataEvent(search: searchController.text));
|
||||
return Future.value(null);
|
||||
}
|
||||
|
||||
void _navToDetails(BuildContext context, CardData data) {
|
||||
Navigator.push(
|
||||
context,
|
||||
@ -138,10 +161,7 @@ class _BodyState extends State<_Body> {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(
|
||||
'$title ${isLiked ? 'liked' : 'unliked'}',
|
||||
style: Theme
|
||||
.of(context)
|
||||
.textTheme
|
||||
.bodyLarge,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
backgroundColor: Colors.orangeAccent,
|
||||
duration: const Duration(seconds: 1),
|
||||
|
Loading…
Reference in New Issue
Block a user