laba 6............
This commit is contained in:
parent
8533648108
commit
a3b65e8c4e
@ -1,4 +1,7 @@
|
|||||||
|
import 'data/dto/album_dto.dart';
|
||||||
|
|
||||||
class CardData {
|
class CardData {
|
||||||
|
final String id;
|
||||||
final String title;
|
final String title;
|
||||||
final String artist;
|
final String artist;
|
||||||
final String year;
|
final String year;
|
||||||
@ -8,5 +11,16 @@ class CardData {
|
|||||||
final String summary;
|
final String summary;
|
||||||
final String? imageUrl;
|
final String? imageUrl;
|
||||||
|
|
||||||
CardData({required this.title, required this.artist, required this.year, required this.url, required this.genres, required this.tracks, required this.summary, required this.imageUrl});
|
CardData({
|
||||||
|
required this.id,
|
||||||
|
required this.title,
|
||||||
|
required this.artist,
|
||||||
|
required this.year,
|
||||||
|
required this.url,
|
||||||
|
required this.genres,
|
||||||
|
required this.tracks,
|
||||||
|
required this.summary,
|
||||||
|
this.imageUrl,
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
22
lib/components/utils/debounce.dart
Normal file
22
lib/components/utils/debounce.dart
Normal 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: 5000),
|
||||||
|
}) {
|
||||||
|
_timer?.cancel();
|
||||||
|
_timer = Timer(delay, action);
|
||||||
|
}
|
||||||
|
}
|
1
lib/components/utils/error_callback.dart
Normal file
1
lib/components/utils/error_callback.dart
Normal file
@ -0,0 +1 @@
|
|||||||
|
typedef OnErrorCallback = void Function(String? error)?;
|
@ -4,10 +4,49 @@ import 'package:uuid/uuid.dart';
|
|||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
class AlbumDto {
|
class AlbumDto {
|
||||||
final List<AlbumDataDto>? data;
|
final List<AlbumDataDto>? data;
|
||||||
|
final AlbumPaginationDto? pagination; // Добавлено для пагинации
|
||||||
|
|
||||||
const AlbumDto({this.data,});
|
const AlbumDto({this.data, this.pagination});
|
||||||
|
|
||||||
|
// Здесь убираем factory и оставляем ваш метод fetchAlbums
|
||||||
|
// factory AlbumDto.fromJson(Map<String, dynamic> json) => _$AlbumDtoFromJson(json);
|
||||||
|
|
||||||
|
// Ваш метод fetchAlbums будет принимать JSON и вызывать конструктор
|
||||||
|
static AlbumDto fetchAlbums(Map<String, dynamic> json) {
|
||||||
|
return AlbumDto(
|
||||||
|
data: (json['data'] as List<dynamic>?)
|
||||||
|
?.map((e) => AlbumDataDto.fromJson(e as Map<String, dynamic>))
|
||||||
|
.toList(),
|
||||||
|
pagination: json['pagination'] != null
|
||||||
|
? AlbumPaginationDto.fromJson(json['pagination'])
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@JsonSerializable(createToJson: false)
|
||||||
|
class AlbumPaginationDto {
|
||||||
|
@JsonKey(name: 'current_page')
|
||||||
|
final int? currentPage;
|
||||||
|
@JsonKey(name: 'has_next_page')
|
||||||
|
final bool? hasNextPage;
|
||||||
|
@JsonKey(name: 'last_visible_page')
|
||||||
|
final int? lastVisiblePage;
|
||||||
|
|
||||||
|
const AlbumPaginationDto({this.currentPage, this.hasNextPage, this.lastVisiblePage});
|
||||||
|
|
||||||
|
// Здесь убираем factory
|
||||||
|
// factory AlbumPaginationDto.fromJson(Map<String, dynamic> json) => _$AlbumPaginationDtoFromJson(json);
|
||||||
|
|
||||||
|
// Метод для конструирования экземпляра
|
||||||
|
static AlbumPaginationDto fromJson(Map<String, dynamic> json) {
|
||||||
|
return AlbumPaginationDto(
|
||||||
|
currentPage: json['current_page'],
|
||||||
|
hasNextPage: json['has_next_page'],
|
||||||
|
lastVisiblePage: json['last_visible_page'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
class AlbumDataDto {
|
class AlbumDataDto {
|
||||||
@ -32,6 +71,26 @@ class AlbumDataDto {
|
|||||||
this.url,
|
this.url,
|
||||||
this.images,
|
this.images,
|
||||||
}) : id = id ?? const Uuid().v4(); // Генерация id
|
}) : id = id ?? const Uuid().v4(); // Генерация id
|
||||||
|
|
||||||
|
// Здесь убираем factory
|
||||||
|
// factory AlbumDataDto.fromJson(Map<String, dynamic> json) => _$AlbumDataDtoFromJson(json);
|
||||||
|
|
||||||
|
// Метод для конструирования экземпляра
|
||||||
|
static AlbumDataDto fromJson(Map<String, dynamic> json) {
|
||||||
|
return AlbumDataDto(
|
||||||
|
id: json['id'],
|
||||||
|
title: json['title'],
|
||||||
|
artist: json['artist'],
|
||||||
|
year: json['year'],
|
||||||
|
genres: (json['genres'] as List<dynamic>?)?.map((e) => e as String).toList(),
|
||||||
|
tracks: (json['tracks'] as List<dynamic>?)?.map((e) => e as String).toList(),
|
||||||
|
summary: json['summary'],
|
||||||
|
url: json['url'],
|
||||||
|
images: json['images'] != null
|
||||||
|
? AlbumDataImagesDto.fromJson(json['images'])
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
@ -39,6 +98,18 @@ class AlbumDataImagesDto {
|
|||||||
final AlbumDataImagesJPGDto? jpg;
|
final AlbumDataImagesJPGDto? jpg;
|
||||||
|
|
||||||
const AlbumDataImagesDto({this.jpg});
|
const AlbumDataImagesDto({this.jpg});
|
||||||
|
|
||||||
|
// Здесь убираем factory
|
||||||
|
// factory AlbumDataImagesDto.fromJson(Map<String, dynamic> json) => _$AlbumDataImagesDtoFromJson(json);
|
||||||
|
|
||||||
|
// Метод для конструирования экземпляра
|
||||||
|
static AlbumDataImagesDto fromJson(Map<String, dynamic> json) {
|
||||||
|
return AlbumDataImagesDto(
|
||||||
|
jpg: json['jpg'] != null
|
||||||
|
? AlbumDataImagesJPGDto.fromJson(json['jpg'])
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonSerializable(createToJson: false)
|
@JsonSerializable(createToJson: false)
|
||||||
@ -46,4 +117,14 @@ class AlbumDataImagesJPGDto {
|
|||||||
final String? image_url;
|
final String? image_url;
|
||||||
|
|
||||||
const AlbumDataImagesJPGDto({this.image_url});
|
const AlbumDataImagesJPGDto({this.image_url});
|
||||||
|
|
||||||
|
// Здесь убираем factory
|
||||||
|
// factory AlbumDataImagesJPGDto.fromJson(Map<String, dynamic> json) => _$AlbumDataImagesJPGDtoFromJson(json);
|
||||||
|
|
||||||
|
// Метод для конструирования экземпляра
|
||||||
|
static AlbumDataImagesJPGDto fromJson(Map<String, dynamic> json) {
|
||||||
|
return AlbumDataImagesJPGDto(
|
||||||
|
image_url: json['image_url'],
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
@ -3,10 +3,15 @@ import 'dart:convert';
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:pmd_labs/data/dto/album_dto.dart';
|
import 'package:pmd_labs/data/dto/album_dto.dart';
|
||||||
import 'package:pmd_labs/card_data.dart';
|
import 'package:pmd_labs/card_data.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
import '../../home_page/home_page.dart';
|
||||||
|
|
||||||
extension AlbumDataDtoMapper on AlbumDataDto {
|
extension AlbumDataDtoMapper on AlbumDataDto {
|
||||||
List<AlbumDataDto> fetchAlbums(List<dynamic> albumsData) {
|
List<AlbumDataDto> fetchAlbums(List<dynamic> albumsData) {
|
||||||
|
const String defaultImageUrl = "https://i.ibb.co/VwCkRD4/image.jpg";
|
||||||
List<AlbumDataDto> albums = [];
|
List<AlbumDataDto> albums = [];
|
||||||
|
final Uuid uuid = Uuid();
|
||||||
|
|
||||||
for (var album in albumsData) {
|
for (var album in albumsData) {
|
||||||
// Ищем изображение с самым большим размером
|
// Ищем изображение с самым большим размером
|
||||||
@ -15,34 +20,30 @@ extension AlbumDataDtoMapper on AlbumDataDto {
|
|||||||
// Ищем наиболее подходящее изображение
|
// Ищем наиболее подходящее изображение
|
||||||
List<dynamic> images = album['image'] as List<dynamic>;
|
List<dynamic> images = album['image'] as List<dynamic>;
|
||||||
var largestImage = images.firstWhere(
|
var largestImage = images.firstWhere(
|
||||||
(image) => image['size'] == 'mega',
|
(image) => image['size'] == 'mega',
|
||||||
orElse: () =>
|
orElse: () => images.firstWhere(
|
||||||
images.firstWhere(
|
(image) => image['size'] == 'extralarge',
|
||||||
(image) => image['size'] == 'extralarge',
|
orElse: () => images.firstWhere(
|
||||||
orElse: () =>
|
(image) => image['size'] == 'large',
|
||||||
images.firstWhere(
|
orElse: () => null, // запасной вариант
|
||||||
(image) => image['size'] == 'large',
|
),
|
||||||
orElse: () => images.first // запасной вариант
|
),
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
if(largestImage['#text'] != "")
|
||||||
albumImage = largestImage['#text'] as String?;
|
albumImage = largestImage['#text'] as String?;
|
||||||
|
else
|
||||||
|
albumImage = defaultImageUrl;
|
||||||
|
|
||||||
if (album['name'] != "(null)" && album['artist'] != "(null)") {
|
if (album['name'] != "(null)" && album['artist'] != "(null)") {
|
||||||
|
final id = uuid.v4();
|
||||||
albums.add(AlbumDataDto(
|
albums.add(AlbumDataDto(
|
||||||
id: null,
|
id: id,
|
||||||
// Вы можете установить значение id, если оно доступно
|
|
||||||
title: album['name'] as String?,
|
title: album['name'] as String?,
|
||||||
artist: album['artist'] as String?,
|
artist: album['artist'] as String?,
|
||||||
year: "",
|
year: "",
|
||||||
// Год будет заполнен позже
|
|
||||||
genres: [],
|
genres: [],
|
||||||
// Позже будет заполнен из второго респонса
|
|
||||||
tracks: [],
|
tracks: [],
|
||||||
// Позже будет заполнен из второго респонса
|
|
||||||
summary: "",
|
summary: "",
|
||||||
// Описание
|
|
||||||
url: album['url'] as String?,
|
url: album['url'] as String?,
|
||||||
images: AlbumDataImagesDto(
|
images: AlbumDataImagesDto(
|
||||||
jpg: AlbumDataImagesJPGDto(image_url: albumImage),
|
jpg: AlbumDataImagesJPGDto(image_url: albumImage),
|
||||||
@ -53,8 +54,7 @@ extension AlbumDataDtoMapper on AlbumDataDto {
|
|||||||
return albums;
|
return albums;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<AlbumDataDto> fetchAlbumDetails(Map<String, dynamic> data,
|
Future<AlbumDataDto> fetchAlbumDetails(Map<String, dynamic> data, AlbumDataDto album) async {
|
||||||
AlbumDataDto album) async {
|
|
||||||
if (data['album'] != null) {
|
if (data['album'] != null) {
|
||||||
// Получаем жанры и год
|
// Получаем жанры и год
|
||||||
String year = "";
|
String year = "";
|
||||||
@ -86,7 +86,7 @@ extension AlbumDataDtoMapper on AlbumDataDto {
|
|||||||
|
|
||||||
// Обновляем дополнительную информацию, если необходимо
|
// Обновляем дополнительную информацию, если необходимо
|
||||||
album.summary =
|
album.summary =
|
||||||
data['album']?['wiki']?['summary'] ?? "missing";// или аналогичное поле
|
data['album']?['wiki']?['summary'] ?? "missing"; // или аналогичное поле
|
||||||
}
|
}
|
||||||
|
|
||||||
return album; // возвращаем заполненное DTO
|
return album; // возвращаем заполненное DTO
|
||||||
@ -94,6 +94,7 @@ extension AlbumDataDtoMapper on AlbumDataDto {
|
|||||||
|
|
||||||
CardData toDomain() {
|
CardData toDomain() {
|
||||||
return CardData(
|
return CardData(
|
||||||
|
id: id,
|
||||||
title: title ?? 'UNKNOWN',
|
title: title ?? 'UNKNOWN',
|
||||||
artist: artist ?? 'UNKNOWN',
|
artist: artist ?? 'UNKNOWN',
|
||||||
year: year ?? 'UNKNOWN',
|
year: year ?? 'UNKNOWN',
|
||||||
@ -101,8 +102,27 @@ extension AlbumDataDtoMapper on AlbumDataDto {
|
|||||||
summary: summary ?? 'UNKNOWN',
|
summary: summary ?? 'UNKNOWN',
|
||||||
genres: genres ?? ['UNKNOWN'],
|
genres: genres ?? ['UNKNOWN'],
|
||||||
tracks: tracks ?? ['UNKNOWN'],
|
tracks: tracks ?? ['UNKNOWN'],
|
||||||
imageUrl: images?.jpg?.image_url ??
|
imageUrl: images?.jpg?.image_url ?? 'UNKNOWN', // Привязываем imageUrl к DTO
|
||||||
'UNKNOWN', // Привязываем imageUrl к DTO
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AlbumDtoMapper on AlbumDto {
|
||||||
|
List<AlbumDataDto> fetchAlbumsWithPagination(List<dynamic> albumsData) {
|
||||||
|
// Используем существующий метод для извлечения данных альбомов
|
||||||
|
List<AlbumDataDto> albums = AlbumDataDto().fetchAlbums(albumsData);
|
||||||
|
|
||||||
|
// Другие манипуляции с пагинацией можно добавить здесь,
|
||||||
|
// если получены дополнительные данные пагинации и необходим их анализ
|
||||||
|
return albums;
|
||||||
|
}
|
||||||
|
|
||||||
|
HomeData toDomain() {
|
||||||
|
return HomeData(
|
||||||
|
data: data?.map((e) => e.toDomain()).toList(),
|
||||||
|
nextPage: (pagination?.hasNextPage ?? false)
|
||||||
|
? ((pagination?.currentPage ?? 0) + 1)
|
||||||
|
: null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -18,12 +18,13 @@ class AlbumRepository extends ApiInterface {
|
|||||||
static const String apiKey = '535d9d508a785fae99bfb492d8f15a58';
|
static const String apiKey = '535d9d508a785fae99bfb492d8f15a58';
|
||||||
static const String _baseUrl = 'https://api.your_album_api.com'; // Замените на ваш базовый URL
|
static const String _baseUrl = 'https://api.your_album_api.com'; // Замените на ваш базовый URL
|
||||||
|
|
||||||
// Метод для загрузки списка альбомов по названию
|
// Метод для загрузки списка альбомов по названию с учетом пагинации
|
||||||
@override
|
@override
|
||||||
Future<List<CardData>?> loadData({String? albumName}) async {
|
Future<List<CardData>?> loadData({String? albumName, int page = 1, int pageSize = 5}) async {
|
||||||
albumName ??= 'a';
|
if (albumName == null || albumName == "")
|
||||||
|
albumName = 'a';
|
||||||
final String url =
|
final String url =
|
||||||
'https://ws.audioscrobbler.com/2.0/?method=album.search&album=$albumName&api_key=$apiKey&format=json';
|
'https://ws.audioscrobbler.com/2.0/?method=album.search&album=$albumName&api_key=$apiKey&format=json&limit=$pageSize&page=$page';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final response = await _dio.get(url);
|
final response = await _dio.get(url);
|
||||||
@ -45,8 +46,7 @@ class AlbumRepository extends ApiInterface {
|
|||||||
// Получение информации об альбоме
|
// Получение информации об альбоме
|
||||||
Future<AlbumDataDto?> getAlbumInfo(AlbumDataDto album) async {
|
Future<AlbumDataDto?> getAlbumInfo(AlbumDataDto album) async {
|
||||||
final String url =
|
final String url =
|
||||||
'https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=$apiKey&artist=${album
|
'https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=$apiKey&artist=${album.artist}&album=${album.title}&format=json';
|
||||||
.artist}&album=${album.title}&format=json';
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final response = await _dio.get(url);
|
final response = await _dio.get(url);
|
||||||
|
18
lib/home_page/bloc/events.dart
Normal file
18
lib/home_page/bloc/events.dart
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import 'package:equatable/equatable.dart';
|
||||||
|
|
||||||
|
abstract class HomeEvent extends Equatable {
|
||||||
|
const HomeEvent();
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<Object?> get props => [];
|
||||||
|
}
|
||||||
|
|
||||||
|
class HomeLoadDataEvent extends HomeEvent {
|
||||||
|
final String? search;
|
||||||
|
final int? nextPage;
|
||||||
|
|
||||||
|
const HomeLoadDataEvent({this.search, this.nextPage});
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<Object?> get props => [search, nextPage];
|
||||||
|
}
|
42
lib/home_page/bloc/home_bloc.dart
Normal file
42
lib/home_page/bloc/home_bloc.dart
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:pmd_labs/data/repositories/album_repository.dart';
|
||||||
|
import 'package:pmd_labs/home_page/bloc/state.dart';
|
||||||
|
import '../home_page.dart';
|
||||||
|
import 'events.dart';
|
||||||
|
|
||||||
|
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
||||||
|
final AlbumRepository 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));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final data = await repo.loadData(albumName: event.search, page: event.nextPage ?? 1);
|
||||||
|
|
||||||
|
HomeData? updatedData;
|
||||||
|
Set<String> existingIds;
|
||||||
|
if (event.nextPage != null && state.data != null) {
|
||||||
|
final existingData = state.data!.data ?? [];
|
||||||
|
final newDataList = data;
|
||||||
|
existingIds = existingData.map((item) => item.id).toSet();
|
||||||
|
final newData = newDataList?.where((newItem) => !existingIds.contains(newItem.id)).toList();
|
||||||
|
updatedData = HomeData(data: [...existingData, ...?newData], nextPage: (event.nextPage ?? 1) + 1);
|
||||||
|
} else {
|
||||||
|
updatedData = HomeData(data: data, nextPage: (event.nextPage ?? 1) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(state.copyWith(data: updatedData, isLoading: false, isPaginationLoading: false));
|
||||||
|
} catch (e) {
|
||||||
|
emit(state.copyWith(isLoading: false, isPaginationLoading: false));
|
||||||
|
print("Error loading data: $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
27
lib/home_page/bloc/state.dart
Normal file
27
lib/home_page/bloc/state.dart
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import 'package:equatable/equatable.dart';
|
||||||
|
import 'package:pmd_labs/card_data.dart';
|
||||||
|
|
||||||
|
import '../home_page.dart'; // Обязательно импортируем CardData
|
||||||
|
|
||||||
|
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,
|
||||||
|
}) {
|
||||||
|
return HomeState(
|
||||||
|
data: data ?? this.data,
|
||||||
|
isLoading: isLoading ?? this.isLoading,
|
||||||
|
isPaginationLoading: isPaginationLoading ?? this.isPaginationLoading,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
List<Object?> get props => [data, isLoading, isPaginationLoading];
|
||||||
|
}
|
@ -1,27 +1,21 @@
|
|||||||
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_labs/components/utils/debounce.dart';
|
||||||
import 'package:pmd_labs/data/repositories/album_repository.dart';
|
import 'package:pmd_labs/data/repositories/album_repository.dart';
|
||||||
import 'package:pmd_labs/details_page/detail_page.dart';
|
import 'package:pmd_labs/details_page/detail_page.dart';
|
||||||
|
import 'package:pmd_labs/home_page/bloc/events.dart';
|
||||||
|
import 'package:pmd_labs/home_page/bloc/state.dart';
|
||||||
import 'package:pmd_labs/card_data.dart';
|
import 'package:pmd_labs/card_data.dart';
|
||||||
|
|
||||||
import '../data/dto/album_dto.dart';
|
import '../data/dto/album_dto.dart';
|
||||||
|
import 'bloc/home_bloc.dart';
|
||||||
|
|
||||||
part 'card.dart';
|
part 'card.dart';
|
||||||
|
|
||||||
|
|
||||||
class MyHomePage extends StatefulWidget {
|
class MyHomePage extends StatefulWidget {
|
||||||
const MyHomePage({super.key, required this.title});
|
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;
|
final String title;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@ -32,20 +26,20 @@ class _MyHomePageState extends State<MyHomePage> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
backgroundColor: const Color(0xFF231a24), // Цвет фона AppBar
|
backgroundColor: const Color(0xFF231a24),
|
||||||
title: Text(
|
title: Text(
|
||||||
widget.title,
|
widget.title,
|
||||||
style: Theme.of(context)
|
style: Theme.of(context)
|
||||||
.textTheme
|
.textTheme
|
||||||
.headlineLarge
|
.headlineLarge
|
||||||
?.copyWith(color: Colors.orange), // Цвет текста заголовка
|
?.copyWith(color: Colors.orange),
|
||||||
),
|
|
||||||
),
|
|
||||||
body: Container(
|
|
||||||
color: const Color(0xFF403042),
|
|
||||||
child: const Body(), // Ваш виджет Body
|
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
body: Container(
|
||||||
|
color: const Color(0xFF403042),
|
||||||
|
child: const Body(), // Ваш виджет Body
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -59,17 +53,37 @@ class Body extends StatefulWidget {
|
|||||||
|
|
||||||
class _BodyState extends State<Body> {
|
class _BodyState extends State<Body> {
|
||||||
final AlbumRepository repo = AlbumRepository();
|
final AlbumRepository repo = AlbumRepository();
|
||||||
var data = AlbumRepository().loadData();
|
final ScrollController scrollController = ScrollController();
|
||||||
|
final TextEditingController searchController = TextEditingController();
|
||||||
|
late final Debounce debounce;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState(); // Настройка времени дебаунса
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
context.read<HomeBloc>().add(const HomeLoadDataEvent());
|
||||||
|
});
|
||||||
|
|
||||||
|
scrollController.addListener(_onNextPageListener);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onNextPageListener() {
|
||||||
|
if (scrollController.position.pixels >= scrollController.position.maxScrollExtent &&
|
||||||
|
!context.read<HomeBloc>().state.isPaginationLoading) {
|
||||||
|
final bloc = context.read<HomeBloc>();
|
||||||
|
bloc.add(HomeLoadDataEvent(
|
||||||
|
search: searchController.text,
|
||||||
|
nextPage: bloc.state.data?.nextPage,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void _showSnackbar(BuildContext context, String title, bool isLiked) {
|
void _showSnackbar(BuildContext context, String title, bool isLiked) {
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
content: Text(
|
content: Text(
|
||||||
'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}',
|
'Лайк на $title ${isLiked ? 'поставлен' : 'убран'}',
|
||||||
style: Theme
|
style: Theme.of(context).textTheme.bodyLarge,
|
||||||
.of(context)
|
|
||||||
.textTheme
|
|
||||||
.bodyLarge,
|
|
||||||
),
|
),
|
||||||
backgroundColor: Colors.orangeAccent,
|
backgroundColor: Colors.orangeAccent,
|
||||||
duration: const Duration(seconds: 1),
|
duration: const Duration(seconds: 1),
|
||||||
@ -79,48 +93,86 @@ class _BodyState extends State<Body> {
|
|||||||
|
|
||||||
void _navToDetails(BuildContext context, CardData data) {
|
void _navToDetails(BuildContext context, CardData data) {
|
||||||
Navigator.push(
|
Navigator.push(
|
||||||
context, CupertinoPageRoute(builder: (context) => DetailsPage(data)));
|
context,
|
||||||
|
CupertinoPageRoute(builder: (context) => DetailsPage(data))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
|
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
|
||||||
child: Column(
|
child: Column(
|
||||||
children: [
|
children: [
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
child: CupertinoSearchTextField(
|
child: CupertinoSearchTextField(
|
||||||
onChanged: (search) {
|
controller: searchController,
|
||||||
setState(() {
|
onChanged: (search) {
|
||||||
data = repo.loadData(albumName:search);
|
Debounce.run(() {
|
||||||
});
|
context.read<HomeBloc>().add(HomeLoadDataEvent(search: search));
|
||||||
},
|
});
|
||||||
style: TextStyle(color: Colors.orange, fontFamily: 'Correction_Tape'),
|
},
|
||||||
),
|
style: TextStyle(color: Colors.orange, fontFamily: 'Correction_Tape'),
|
||||||
),
|
),
|
||||||
Expanded(child: Center(
|
),
|
||||||
child: FutureBuilder<List<CardData>?>(
|
Expanded(
|
||||||
future: data,
|
child: BlocBuilder<HomeBloc, HomeState>(
|
||||||
builder: (context, snapshot) =>
|
builder: (context, state) {
|
||||||
SingleChildScrollView(
|
if (state.isLoading) {
|
||||||
child: snapshot.hasData ? Column(
|
return const Center(child: CircularProgressIndicator());
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
}
|
||||||
children: snapshot.data!.map((data) {
|
return RefreshIndicator(
|
||||||
return _Card.fromData(data,
|
onRefresh: () async {
|
||||||
onLike: (String title, bool isLiked) =>
|
// Добавим состояние загрузки
|
||||||
_showSnackbar(context, title, isLiked),
|
context.read<HomeBloc>().add(HomeLoadDataEvent(search: searchController.text));
|
||||||
onTap: () => _navToDetails(context, data),);
|
},
|
||||||
}).toList() ?? [],
|
child: ListView.builder(
|
||||||
|
controller: scrollController,
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
itemCount: state.data?.data?.length ?? 0,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final cardData = state.data?.data?[index];
|
||||||
|
return cardData != null
|
||||||
|
? _Card.fromData(
|
||||||
|
cardData,
|
||||||
|
onLike: (title, isLiked) => _showSnackbar(context, title, isLiked),
|
||||||
|
onTap: () => _navToDetails(context, cardData),
|
||||||
)
|
)
|
||||||
: const CircularProgressIndicator(),
|
: const SizedBox.shrink();
|
||||||
),
|
},
|
||||||
),
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
)
|
),
|
||||||
],
|
BlocBuilder<HomeBloc, HomeState>(
|
||||||
|
builder: (context, state) {
|
||||||
|
if (state.isPaginationLoading) {
|
||||||
|
return const Padding(
|
||||||
|
padding: EdgeInsets.all(8.0),
|
||||||
|
child: CircularProgressIndicator(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
));
|
@override
|
||||||
}}
|
void dispose() {
|
||||||
|
searchController.dispose();
|
||||||
|
scrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class HomeData {
|
||||||
|
final List<CardData>? data;
|
||||||
|
final int? nextPage;
|
||||||
|
|
||||||
|
HomeData({this.data, this.nextPage});
|
||||||
|
}
|
@ -1,6 +1,11 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:pmd_labs/data/repositories/album_repository.dart';
|
||||||
import 'package:pmd_labs/home_page/home_page.dart';
|
import 'package:pmd_labs/home_page/home_page.dart';
|
||||||
|
|
||||||
|
import 'home_page/bloc/home_bloc.dart';
|
||||||
|
import 'home_page/home_page.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
runApp(const MyApp());
|
runApp(const MyApp());
|
||||||
}
|
}
|
||||||
@ -12,7 +17,7 @@ class MyApp extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'Flutter Demo',
|
title: 'Лабы ПМУ',
|
||||||
theme: ThemeData(
|
theme: ThemeData(
|
||||||
textTheme: const TextTheme(
|
textTheme: const TextTheme(
|
||||||
headlineLarge: TextStyle(fontFamily: 'Correction_Tape'),
|
headlineLarge: TextStyle(fontFamily: 'Correction_Tape'),
|
||||||
@ -23,7 +28,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: 'Catalog of Music Albums'),
|
home: RepositoryProvider<AlbumRepository>(
|
||||||
|
lazy: true,
|
||||||
|
create: (_) => AlbumRepository(),
|
||||||
|
child: BlocProvider<HomeBloc>(
|
||||||
|
lazy: false,
|
||||||
|
create: (context) => HomeBloc(context.read<AlbumRepository>()),
|
||||||
|
child: const MyHomePage(title: 'Catalog of Music Albums'),
|
||||||
|
),
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
40
pubspec.lock
40
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: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.7"
|
||||||
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:
|
||||||
@ -400,6 +424,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.0"
|
version: "2.0.0"
|
||||||
|
nested:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: nested
|
||||||
|
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.0.0"
|
||||||
package_config:
|
package_config:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@ -432,6 +464,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.0"
|
version: "1.4.0"
|
||||||
|
provider:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: provider
|
||||||
|
sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.1.2"
|
||||||
pub_semver:
|
pub_semver:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
@ -40,6 +40,8 @@ dependencies:
|
|||||||
pretty_dio_logger: ^1.3.1
|
pretty_dio_logger: ^1.3.1
|
||||||
http: ^0.13.3
|
http: ^0.13.3
|
||||||
uuid: ^3.0.5
|
uuid: ^3.0.5
|
||||||
|
equatable: ^2.0.7
|
||||||
|
flutter_bloc: ^8.1.6
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user