You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import 'dart:async'; import 'dart:convert'; import 'dart:math';
import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:sonnat/core/utils/base_cubit_type.dart'; import 'package:sonnat/features/single_post/view_models/post.dart';
class PostsCubit extends Cubit<BaseCubitType<PostsState>> { List<Post> allData = []; List<Post> postList = []; List<Post> searchedList = []; bool hasReachedMax = false; String _query = '';
PostsCubit() : super(BaseCubitType(eventName: PostsState.empty));
void empty() => emit(BaseCubitType(eventName: PostsState.empty));
Future<void> getData() async { if (hasReachedMax) { return; } if (postList.isNotEmpty) { emit(BaseCubitType(eventName: PostsState.loadingPagination)); } else { emit(BaseCubitType(eventName: PostsState.loading)); } String data = await rootBundle.loadString('assets/meta/data.json'); allData = List<Post>.from( jsonDecode(data)['posts'].map( (post) => Post.fromJson(post).copyWith(DateTime.now().millisecondsSinceEpoch), ), ); if (allData.isNotEmpty) { List<Post> posts = allData.getRange(postList.length, min(postList.length + 20, allData.length)).toList(); hasReachedMax = posts.length < 20; postList += posts; emit(BaseCubitType(eventName: PostsState.data)); } else { emit(BaseCubitType(eventName: PostsState.data)); } }
Future<void> search({required String query}) async { if (query.isEmpty) { unawaited(getData()); _query = ''; searchedList.clear(); emit(BaseCubitType(eventName: PostsState.data)); return; } if (_query != query) { hasReachedMax = false; searchedList.clear(); _query = query; } if (hasReachedMax) { return; } if (searchedList.isNotEmpty) { emit(BaseCubitType(eventName: PostsState.loadingPagination)); } else { emit(BaseCubitType(eventName: PostsState.loading)); } await Future.delayed(Duration(milliseconds: Random().nextInt(1000))); String data = await rootBundle.loadString('assets/meta/data.json'); allData = List<Post>.from( jsonDecode(data)['posts'].map( (post) => Post.fromJson(post).copyWith( DateTime.now().millisecondsSinceEpoch, ), ), ); if (allData.isNotEmpty) { List<Post> posts = allData.where((element) => element.name.contains(query.trim())).toList(); hasReachedMax = posts.length < 20; searchedList += posts; emit(BaseCubitType(eventName: PostsState.data)); } else { emit(BaseCubitType(eventName: PostsState.data)); } }
String get query => _query;
void clearSearch() { unawaited(getData()); _query = ''; searchedList.clear(); emit(BaseCubitType(eventName: PostsState.data)); }
Future<void> changeFilter(int index) async { emit(BaseCubitType(eventName: PostsState.changeFilterIndex, data: index)); await Future.delayed(Duration(milliseconds: Random().nextInt(1000))); await getData(); } }
enum PostsState { empty, data, loading, loadingPagination, changeFilterIndex, }
|