elCaribe app - customization and branding
This commit is contained in:
258
news-app/lib/app/app.dart
Normal file
258
news-app/lib/app/app.dart
Normal file
@@ -0,0 +1,258 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
||||
import 'package:hive_flutter/adapters.dart';
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
import 'package:news/app/routes.dart';
|
||||
import 'package:news/cubits/AddNewsCubit.dart';
|
||||
import 'package:news/cubits/Auth/deleteUserCubit.dart';
|
||||
import 'package:news/cubits/Auth/registerTokenCubit.dart';
|
||||
import 'package:news/cubits/Auth/updateUserCubit.dart';
|
||||
import 'package:news/cubits/Author/authorCubit.dart';
|
||||
import 'package:news/cubits/Author/authorNewsCubit.dart';
|
||||
import 'package:news/cubits/Bookmark/UpdateBookmarkCubit.dart';
|
||||
import 'package:news/cubits/Bookmark/bookmarkCubit.dart';
|
||||
import 'package:news/cubits/ConnectivityCubit.dart';
|
||||
import 'package:news/cubits/LikeAndDislikeNews/LikeAndDislikeCubit.dart';
|
||||
import 'package:news/cubits/LikeAndDislikeNews/updateLikeAndDislikeCubit.dart';
|
||||
import 'package:news/cubits/NewsComment/deleteCommentCubit.dart';
|
||||
import 'package:news/cubits/NewsComment/flagCommentCubit.dart';
|
||||
import 'package:news/cubits/NewsComment/likeAndDislikeCommCubit.dart';
|
||||
import 'package:news/cubits/NewsComment/setCommentCubit.dart';
|
||||
import 'package:news/cubits/UserPreferences/setUserPreferenceCatCubit.dart';
|
||||
import 'package:news/cubits/adSpacesNewsDetailsCubit.dart';
|
||||
import 'package:news/cubits/appLocalizationCubit.dart';
|
||||
import 'package:news/cubits/Auth/authCubit.dart';
|
||||
import 'package:news/cubits/breakingNewsCubit.dart';
|
||||
import 'package:news/cubits/commentNewsCubit.dart';
|
||||
import 'package:news/cubits/deleteImageId.dart';
|
||||
import 'package:news/cubits/deleteUserNewsCubit.dart';
|
||||
import 'package:news/cubits/generalNewsCubit.dart';
|
||||
import 'package:news/cubits/getSurveyAnswerCubit.dart';
|
||||
import 'package:news/cubits/getUserDataByIdCubit.dart';
|
||||
import 'package:news/cubits/getUserNewsCubit.dart';
|
||||
import 'package:news/cubits/languageCubit.dart';
|
||||
import 'package:news/cubits/locationCityCubit.dart';
|
||||
import 'package:news/cubits/privacyTermsCubit.dart';
|
||||
import 'package:news/cubits/relatedNewsCubit.dart';
|
||||
import 'package:news/cubits/rssFeedCubit.dart';
|
||||
import 'package:news/cubits/sectionByIdCubit.dart';
|
||||
import 'package:news/cubits/setNewsViewsCubit.dart';
|
||||
import 'package:news/cubits/setSurveyAnswerCubit.dart';
|
||||
import 'package:news/cubits/settingCubit.dart';
|
||||
import 'package:news/cubits/Auth/socialSignUpCubit.dart';
|
||||
import 'package:news/cubits/UserPreferences/userByCategoryCubit.dart';
|
||||
import 'package:news/cubits/slugCheckCubit.dart';
|
||||
import 'package:news/cubits/slugNewsCubit.dart';
|
||||
import 'package:news/cubits/tagCubit.dart';
|
||||
import 'package:news/cubits/tagNewsCubit.dart';
|
||||
import 'package:news/cubits/NewsByIdCubit.dart';
|
||||
import 'package:news/cubits/appSystemSettingCubit.dart';
|
||||
import 'package:news/cubits/categoryCubit.dart';
|
||||
import 'package:news/cubits/featureSectionCubit.dart';
|
||||
import 'package:news/cubits/languageJsonCubit.dart';
|
||||
import 'package:news/cubits/liveStreamCubit.dart';
|
||||
import 'package:news/cubits/otherPagesCubit.dart';
|
||||
import 'package:news/cubits/subCategoryCubit.dart';
|
||||
import 'package:news/cubits/surveyQuestionCubit.dart';
|
||||
import 'package:news/cubits/themeCubit.dart';
|
||||
import 'package:news/cubits/updateBottomsheetContentCubit.dart';
|
||||
import 'package:news/cubits/videosCubit.dart';
|
||||
import 'package:news/cubits/weatherCubit.dart';
|
||||
import 'package:news/cubits/GetUserDraftedNewsCubit.dart';
|
||||
import 'package:news/data/repositories/AddNews/addNewsRepository.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
import 'package:news/data/repositories/Bookmark/bookmarkRepository.dart';
|
||||
import 'package:news/data/repositories/BreakingNews/breakNewsRepository.dart';
|
||||
import 'package:news/data/repositories/CommentNews/commNewsRepository.dart';
|
||||
import 'package:news/data/repositories/DeleteImageId/deleteImageRepository.dart';
|
||||
import 'package:news/data/repositories/DeleteUserNews/deleteUserNewsRepository.dart';
|
||||
import 'package:news/data/repositories/GetSurveyAnswer/getSurveyAnsRepository.dart';
|
||||
import 'package:news/data/repositories/GetUserById/getUserByIdRepository.dart';
|
||||
import 'package:news/data/repositories/GetUserNews/getUserNewsRepository.dart';
|
||||
import 'package:news/data/repositories/LikeAndDisLikeNews/LikeAndDisLikeNewsRepository.dart';
|
||||
import 'package:news/data/repositories/NewsComment/DeleteComment/deleteCommRepository.dart';
|
||||
import 'package:news/data/repositories/NewsComment/FlagComment/flagCommRepository.dart';
|
||||
import 'package:news/data/repositories/NewsComment/LikeAndDislikeComment/likeAndDislikeCommRepository.dart';
|
||||
import 'package:news/data/repositories/NewsComment/SetComment/setComRepository.dart';
|
||||
import 'package:news/data/repositories/RelatedNews/relatedNewsRepository.dart';
|
||||
import 'package:news/data/repositories/SectionById/sectionByIdRepository.dart';
|
||||
import 'package:news/data/repositories/SetNewsViews/setNewsViewsRepository.dart';
|
||||
import 'package:news/data/repositories/SetSurveyAnswer/setSurveyAnsRepository.dart';
|
||||
import 'package:news/data/repositories/SetUserPreferenceCat/setUserPrefCatRepository.dart';
|
||||
import 'package:news/data/repositories/SurveyQuestion/surveyQueRepository.dart';
|
||||
import 'package:news/data/repositories/Tag/tagRepository.dart';
|
||||
import 'package:news/data/repositories/TagNews/tagNewsRepository.dart';
|
||||
import 'package:news/data/repositories/UserByCategory/userByCatRepository.dart';
|
||||
import 'package:news/data/repositories/language/languageRepository.dart';
|
||||
import 'package:news/data/repositories/Settings/settingRepository.dart';
|
||||
import 'package:news/data/repositories/Settings/settingsLocalDataRepository.dart';
|
||||
import 'package:news/data/repositories/AppSystemSetting/systemRepository.dart';
|
||||
import 'package:news/data/repositories/Category/categoryRepository.dart';
|
||||
import 'package:news/data/repositories/FeatureSection/sectionRepository.dart';
|
||||
import 'package:news/data/repositories/LanguageJson/languageJsonRepository.dart';
|
||||
import 'package:news/data/repositories/LiveStream/liveStreamRepository.dart';
|
||||
import 'package:news/data/repositories/NewsById/NewsByIdRepository.dart';
|
||||
import 'package:news/data/repositories/OtherPages/otherPagesRepository.dart';
|
||||
import 'package:news/data/repositories/SubCategory/subCatRepository.dart';
|
||||
import 'package:news/data/repositories/Videos/videosRepository.dart';
|
||||
import 'package:news/ui/screens/PushNotificationService.dart';
|
||||
import 'package:news/ui/styles/appTheme.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/hiveBoxKeys.dart';
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
|
||||
late PackageInfo packageInfo;
|
||||
|
||||
Future<void> initializeApp() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
HttpOverrides.global = MyHttpOverrides();
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
|
||||
MobileAds.instance.initialize();
|
||||
|
||||
packageInfo = await PackageInfo.fromPlatform();
|
||||
|
||||
await Firebase.initializeApp();
|
||||
|
||||
await Hive.initFlutter();
|
||||
|
||||
await Hive.openBox(authBoxKey);
|
||||
|
||||
await Hive.openBox(settingsBoxKey);
|
||||
|
||||
await Hive.openBox(locationCityBoxKey);
|
||||
await Hive.openBox(videoPreferenceKey);
|
||||
|
||||
runApp(MultiBlocProvider(providers: [
|
||||
BlocProvider(create: (_) => ConnectivityCubit(ConnectivityService())),
|
||||
BlocProvider<AppConfigurationCubit>(create: (context) => AppConfigurationCubit(SystemRepository())),
|
||||
BlocProvider<SettingsCubit>(create: (_) => SettingsCubit(SettingsRepository())),
|
||||
BlocProvider<AppLocalizationCubit>(create: (_) => AppLocalizationCubit(SettingsLocalDataRepository())),
|
||||
BlocProvider<ThemeCubit>(create: (_) => ThemeCubit(SettingsLocalDataRepository())),
|
||||
BlocProvider<LanguageJsonCubit>(create: (_) => LanguageJsonCubit(LanguageJsonRepository())),
|
||||
BlocProvider<LanguageCubit>(create: (context) => LanguageCubit(LanguageRepository())),
|
||||
BlocProvider<SectionCubit>(create: (_) => SectionCubit(SectionRepository())),
|
||||
BlocProvider<PrivacyTermsCubit>(create: (_) => PrivacyTermsCubit(OtherPageRepository())),
|
||||
BlocProvider<VideoCubit>(create: (_) => VideoCubit(VideoRepository())),
|
||||
BlocProvider<NewsByIdCubit>(create: (_) => NewsByIdCubit(NewsByIdRepository())),
|
||||
BlocProvider<OtherPageCubit>(create: (_) => OtherPageCubit(OtherPageRepository())),
|
||||
BlocProvider<LiveStreamCubit>(create: (_) => LiveStreamCubit(LiveStreamRepository())),
|
||||
BlocProvider<CategoryCubit>(create: (_) => CategoryCubit(CategoryRepository())),
|
||||
BlocProvider<SubCategoryCubit>(create: (_) => SubCategoryCubit(SubCategoryRepository())),
|
||||
BlocProvider<SurveyQuestionCubit>(create: (_) => SurveyQuestionCubit(SurveyQuestionRepository())),
|
||||
BlocProvider<SetSurveyAnsCubit>(create: (_) => SetSurveyAnsCubit(SetSurveyAnsRepository())),
|
||||
BlocProvider<GetSurveyAnsCubit>(create: (_) => GetSurveyAnsCubit(GetSurveyAnsRepository())),
|
||||
BlocProvider<CommentNewsCubit>(create: (_) => CommentNewsCubit(CommentNewsRepository())),
|
||||
BlocProvider<RelatedNewsCubit>(create: (_) => RelatedNewsCubit(RelatedNewsRepository())),
|
||||
BlocProvider<SocialSignUpCubit>(create: (_) => SocialSignUpCubit(AuthRepository())),
|
||||
BlocProvider<AuthCubit>(create: (_) => AuthCubit(AuthRepository())),
|
||||
BlocProvider<RegisterTokenCubit>(create: (_) => RegisterTokenCubit(AuthRepository())),
|
||||
BlocProvider<UserByCatCubit>(create: (_) => UserByCatCubit(UserByCatRepository())),
|
||||
BlocProvider<SetUserPrefCatCubit>(create: (_) => SetUserPrefCatCubit(SetUserPrefCatRepository())),
|
||||
BlocProvider<UpdateUserCubit>(create: (_) => UpdateUserCubit(AuthRepository())),
|
||||
BlocProvider<DeleteUserCubit>(create: (_) => DeleteUserCubit(AuthRepository())),
|
||||
BlocProvider<BookmarkCubit>(create: (_) => BookmarkCubit(BookmarkRepository())),
|
||||
BlocProvider<UpdateBookmarkStatusCubit>(create: (_) => UpdateBookmarkStatusCubit(BookmarkRepository())),
|
||||
BlocProvider<LikeAndDisLikeCubit>(create: (_) => LikeAndDisLikeCubit(LikeAndDisLikeRepository())),
|
||||
BlocProvider<UpdateLikeAndDisLikeStatusCubit>(create: (_) => UpdateLikeAndDisLikeStatusCubit(LikeAndDisLikeRepository())),
|
||||
BlocProvider<BreakingNewsCubit>(create: (_) => BreakingNewsCubit(BreakingNewsRepository())),
|
||||
BlocProvider<TagNewsCubit>(create: (_) => TagNewsCubit(TagNewsRepository())),
|
||||
BlocProvider<SetCommentCubit>(create: (_) => SetCommentCubit(SetCommentRepository())),
|
||||
BlocProvider<LikeAndDislikeCommCubit>(create: (_) => LikeAndDislikeCommCubit(LikeAndDislikeCommRepository())),
|
||||
BlocProvider<DeleteCommCubit>(create: (_) => DeleteCommCubit(DeleteCommRepository())),
|
||||
BlocProvider<SetFlagCubit>(create: (_) => SetFlagCubit(SetFlagRepository())),
|
||||
BlocProvider<AddNewsCubit>(create: (_) => AddNewsCubit(AddNewsRepository())),
|
||||
BlocProvider<TagCubit>(create: (_) => TagCubit(TagRepository())),
|
||||
BlocProvider<GetUserNewsCubit>(create: (_) => GetUserNewsCubit(GetUserNewsRepository())),
|
||||
BlocProvider<DeleteUserNewsCubit>(create: (_) => DeleteUserNewsCubit(DeleteUserNewsRepository())),
|
||||
BlocProvider<DeleteImageCubit>(create: (_) => DeleteImageCubit(DeleteImageRepository())),
|
||||
BlocProvider<GetUserByIdCubit>(create: (_) => GetUserByIdCubit(GetUserByIdRepository())),
|
||||
BlocProvider<SectionByIdCubit>(create: (_) => SectionByIdCubit(SectionByIdRepository())),
|
||||
BlocProvider<SetNewsViewsCubit>(create: (_) => SetNewsViewsCubit(SetNewsViewsRepository())),
|
||||
BlocProvider<AdSpacesNewsDetailsCubit>(create: (_) => AdSpacesNewsDetailsCubit()),
|
||||
BlocProvider<LocationCityCubit>(create: (_) => LocationCityCubit()),
|
||||
BlocProvider<BottomSheetCubit>(create: (_) => BottomSheetCubit()),
|
||||
BlocProvider<SlugCheckCubit>(create: (_) => SlugCheckCubit()),
|
||||
BlocProvider<GeneralNewsCubit>(create: (_) => GeneralNewsCubit()),
|
||||
BlocProvider<RSSFeedCubit>(create: (_) => RSSFeedCubit()),
|
||||
BlocProvider<SlugNewsCubit>(create: (_) => SlugNewsCubit()),
|
||||
BlocProvider<WeatherCubit>(create: (_) => WeatherCubit()),
|
||||
BlocProvider<AuthorCubit>(create: (_) => AuthorCubit()),
|
||||
BlocProvider<AuthorNewsCubit>(create: (_) => AuthorNewsCubit()),
|
||||
BlocProvider<GetUserDraftedNewsCubit>(create: (_) => GetUserDraftedNewsCubit())
|
||||
], child: const MyApp()));
|
||||
}
|
||||
|
||||
class GlobalScrollBehavior extends ScrollBehavior {
|
||||
@override
|
||||
ScrollPhysics getScrollPhysics(BuildContext context) {
|
||||
return const BouncingScrollPhysics();
|
||||
}
|
||||
}
|
||||
|
||||
class MyApp extends StatefulWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
State<MyApp> createState() => _MyAppState();
|
||||
}
|
||||
|
||||
class _MyAppState extends State<MyApp> {
|
||||
@override
|
||||
void initState() {
|
||||
final pushNotificationService = PushNotificationService(context: context);
|
||||
pushNotificationService.initialise();
|
||||
var brightness = PlatformDispatcher.instance.platformBrightness;
|
||||
if (SettingsLocalDataRepository().getCurrentTheme().isEmpty) {
|
||||
(brightness == Brightness.dark) ? context.read<ThemeCubit>().changeTheme(AppTheme.Dark) : context.read<ThemeCubit>().changeTheme(AppTheme.Light);
|
||||
}
|
||||
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Builder(builder: (context) {
|
||||
if (Hive.box(settingsBoxKey).get(currentLanguageCodeKey) != null || Hive.box(settingsBoxKey).get(currentLanguageCodeKey) != "") {
|
||||
initializeDateFormatting();
|
||||
intl.Intl.defaultLocale = Hive.box(settingsBoxKey).get(currentLanguageCodeKey); //set default Locale @Start
|
||||
}
|
||||
final currentTheme = context.watch<ThemeCubit>().state.appTheme;
|
||||
return BlocBuilder<AppLocalizationCubit, AppLocalizationState>(
|
||||
builder: (context, state) {
|
||||
return MaterialApp(
|
||||
navigatorKey: UiUtils.rootNavigatorKey,
|
||||
theme: appThemeData[currentTheme],
|
||||
debugShowCheckedModeBanner: false,
|
||||
initialRoute: Routes.splash,
|
||||
title: appName,
|
||||
onGenerateRoute: Routes.onGenerateRouted,
|
||||
builder: (context, widget) {
|
||||
return ScrollConfiguration(
|
||||
behavior: GlobalScrollBehavior(),
|
||||
child: Directionality(
|
||||
textDirection: state.isRTL == '' || state.isRTL == 0 ? TextDirection.ltr : TextDirection.rtl,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.viewPaddingOf(context).bottom),
|
||||
child: widget!,
|
||||
)));
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class MyHttpOverrides extends HttpOverrides {
|
||||
@override
|
||||
HttpClient createHttpClient(SecurityContext? context) {
|
||||
return super.createHttpClient(context)..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
|
||||
}
|
||||
}
|
||||
203
news-app/lib/app/routes.dart
Normal file
203
news-app/lib/app/routes.dart
Normal file
@@ -0,0 +1,203 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:news/ui/screens/AddEditNews/AddNews.dart';
|
||||
import 'package:news/ui/screens/BookmarkScreen.dart';
|
||||
import 'package:news/ui/screens/ImagePreviewScreen.dart';
|
||||
import 'package:news/ui/screens/LiveStreaming.dart';
|
||||
import 'package:news/ui/screens/NewsDetail/NewsDetailScreen.dart';
|
||||
import 'package:news/ui/screens/NewsDetail/Widgets/ShowMoreNewsList.dart';
|
||||
import 'package:news/ui/screens/PrivacyPolicyScreen.dart';
|
||||
import 'package:news/ui/screens/Profile/userProfile.dart';
|
||||
import 'package:news/ui/screens/RSSFeedDetailsScreen.dart';
|
||||
import 'package:news/ui/screens/Search.dart';
|
||||
import 'package:news/ui/screens/AddEditNews/ManageUserNews.dart';
|
||||
import 'package:news/ui/screens/SubCategory/SubCategoryScreen.dart';
|
||||
import 'package:news/ui/screens/TagNewsScreen.dart';
|
||||
import 'package:news/ui/screens/Videos/videoDetailsScreen.dart';
|
||||
import 'package:news/ui/screens/auth/ForgotPassword.dart';
|
||||
import 'package:news/ui/screens/auth/RequestOtpScreen.dart';
|
||||
import 'package:news/ui/screens/auth/VerifyOtpScreen.dart';
|
||||
import 'package:news/ui/screens/authorDetailsScreen.dart';
|
||||
import 'package:news/ui/screens/dashBoard/dashBoardScreen.dart';
|
||||
import 'package:news/ui/screens/introSlider.dart';
|
||||
import 'package:news/ui/screens/languageList.dart';
|
||||
import 'package:news/ui/screens/maintenanceScreen.dart';
|
||||
import 'package:news/ui/screens/splashScreen.dart';
|
||||
import 'package:news/ui/screens/ManagePreference.dart';
|
||||
import 'package:news/ui/screens/SectionMoreNews/SectionMoreBreakNewsList.dart';
|
||||
import 'package:news/ui/screens/SectionMoreNews/SectionMoreNewsList.dart';
|
||||
import 'package:news/ui/screens/auth/loginScreen.dart';
|
||||
import 'package:news/ui/widgets/loadingScreen.dart';
|
||||
|
||||
class Routes {
|
||||
static const String splash = "splash";
|
||||
static const String home = "/";
|
||||
static const String introSlider = "introSlider";
|
||||
static const String languageList = "languageList";
|
||||
static const String login = "login";
|
||||
static const String privacy = "privacy";
|
||||
static const String search = "search";
|
||||
static const String live = "live";
|
||||
static const String subCat = "subCat";
|
||||
static const String requestOtp = "requestOtp";
|
||||
static const String verifyOtp = "verifyOtp";
|
||||
static const String managePref = "managePref";
|
||||
static const String newsVideo = "newsVideo";
|
||||
static const String bookmark = "bookmark";
|
||||
static const String newsDetails = "newsDetails";
|
||||
static const String imagePreview = "imagePreview";
|
||||
static const String tagScreen = "tagScreen";
|
||||
static const String addNews = "AddNews";
|
||||
static const String editNews = "editNews";
|
||||
static const String manageUserNews = "showNews";
|
||||
static const String forgotPass = "forgotPass";
|
||||
static const String sectionNews = "sectionNews";
|
||||
static const String sectionBreakNews = "sectionBreakNews";
|
||||
static const String showMoreRelatedNews = "showMoreRelatedNews";
|
||||
static const String editUserProfile = "editUserProfile";
|
||||
static const String maintenance = "maintenance";
|
||||
static const String rssFeedDetails = "rssFeedDetails";
|
||||
static const String authorDetails = "authorDetails";
|
||||
|
||||
static String currentRoute = splash;
|
||||
static String previousRoute = "";
|
||||
|
||||
static Route<dynamic> onGenerateRouted(RouteSettings routeSettings) {
|
||||
previousRoute = currentRoute;
|
||||
currentRoute = routeSettings.name ?? "";
|
||||
|
||||
if (routeSettings.name!.contains('/news/') || routeSettings.name!.contains('/breaking-news/') || routeSettings.name!.contains('/video-news/')) {
|
||||
final String? currNewsSlug = routeSettings.name!.split('/').last.split('?language_id').first;
|
||||
|
||||
if (previousRoute == splash) {
|
||||
//app is closed
|
||||
isShared = true;
|
||||
|
||||
Uri uri = Uri.parse(routeSettings.name!);
|
||||
String path = uri.path;
|
||||
routeSettingsName = path;
|
||||
newsSlug = currNewsSlug;
|
||||
return CupertinoPageRoute(builder: (_) => const Splash());
|
||||
} else {
|
||||
//app is running
|
||||
return CupertinoPageRoute(builder: (_) => LoadingScreen(routeSettingsName: routeSettings.name!, newsSlug: currNewsSlug ?? ""));
|
||||
}
|
||||
}
|
||||
switch (routeSettings.name) {
|
||||
case splash:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const Splash());
|
||||
}
|
||||
case home:
|
||||
{
|
||||
return DashBoard.route(routeSettings);
|
||||
}
|
||||
case introSlider:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const IntroSliderScreen());
|
||||
}
|
||||
case login:
|
||||
{
|
||||
return LoginScreen.route(routeSettings);
|
||||
}
|
||||
case languageList:
|
||||
{
|
||||
return LanguageList.route(routeSettings);
|
||||
}
|
||||
case privacy:
|
||||
{
|
||||
return PrivacyPolicy.route(routeSettings);
|
||||
}
|
||||
case search:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const Search());
|
||||
}
|
||||
case live:
|
||||
{
|
||||
return LiveStreaming.route(routeSettings);
|
||||
}
|
||||
case subCat:
|
||||
{
|
||||
return SubCategoryScreen.route(routeSettings);
|
||||
}
|
||||
case requestOtp:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const RequestOtp());
|
||||
}
|
||||
case verifyOtp:
|
||||
{
|
||||
return VerifyOtp.route(routeSettings);
|
||||
}
|
||||
case managePref:
|
||||
{
|
||||
return ManagePref.route(routeSettings);
|
||||
}
|
||||
case newsVideo:
|
||||
{
|
||||
return VideoDetailsScreen.route(routeSettings);
|
||||
}
|
||||
case bookmark:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const BookmarkScreen());
|
||||
}
|
||||
case newsDetails:
|
||||
{
|
||||
return NewsDetailScreen.route(routeSettings);
|
||||
}
|
||||
case imagePreview:
|
||||
{
|
||||
return ImagePreview.route(routeSettings);
|
||||
}
|
||||
case tagScreen:
|
||||
{
|
||||
return NewsTag.route(routeSettings);
|
||||
}
|
||||
case addNews:
|
||||
{
|
||||
return AddNews.route(routeSettings);
|
||||
}
|
||||
case manageUserNews:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const ManageUserNews());
|
||||
}
|
||||
case forgotPass:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const ForgotPassword());
|
||||
}
|
||||
|
||||
case sectionNews:
|
||||
{
|
||||
return SectionMoreNewsList.route(routeSettings);
|
||||
}
|
||||
case sectionBreakNews:
|
||||
{
|
||||
return SectionMoreBreakingNewsList.route(routeSettings);
|
||||
}
|
||||
case showMoreRelatedNews:
|
||||
{
|
||||
return ShowMoreNewsList.route(routeSettings);
|
||||
}
|
||||
case editUserProfile:
|
||||
{
|
||||
return UserProfileScreen.route(routeSettings);
|
||||
}
|
||||
case maintenance:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (_) => const MaintenanceScreen());
|
||||
}
|
||||
case rssFeedDetails:
|
||||
{
|
||||
return RSSFeedDetailsScreen.route(routeSettings);
|
||||
}
|
||||
case authorDetails:
|
||||
{
|
||||
return AuthorDetailsScreen.route(routeSettings);
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
return CupertinoPageRoute(builder: (context) => const Scaffold());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
86
news-app/lib/cubits/AddNewsCubit.dart
Normal file
86
news-app/lib/cubits/AddNewsCubit.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/AddNews/addNewsRepository.dart';
|
||||
|
||||
abstract class AddNewsState {}
|
||||
|
||||
class AddNewsInitial extends AddNewsState {}
|
||||
|
||||
class AddNewsFetchInProgress extends AddNewsState {}
|
||||
|
||||
class AddNewsFetchSuccess extends AddNewsState {
|
||||
var addNews;
|
||||
|
||||
AddNewsFetchSuccess({required this.addNews});
|
||||
}
|
||||
|
||||
class AddNewsFetchFailure extends AddNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
AddNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class AddNewsCubit extends Cubit<AddNewsState> {
|
||||
final AddNewsRepository _addNewsRepository;
|
||||
|
||||
AddNewsCubit(this._addNewsRepository) : super(AddNewsInitial());
|
||||
|
||||
void addNews(
|
||||
{required BuildContext context,
|
||||
required String actionType,
|
||||
required String catId,
|
||||
required String title,
|
||||
required String conTypeId,
|
||||
required String conType,
|
||||
required String langId,
|
||||
File? image,
|
||||
String? newsId,
|
||||
String? subCatId,
|
||||
String? showTill,
|
||||
String? tagId,
|
||||
String? url,
|
||||
String? desc,
|
||||
String? summDescription,
|
||||
String? locationId,
|
||||
File? videoUpload,
|
||||
List<File>? otherImage,
|
||||
String? publishDate,
|
||||
required String metaTitle,
|
||||
required String metaDescription,
|
||||
required String metaKeyword,
|
||||
required String slug,
|
||||
required int isDraft}) async {
|
||||
try {
|
||||
emit(AddNewsFetchInProgress());
|
||||
final result = await _addNewsRepository.addNews(
|
||||
context: context,
|
||||
actionType: actionType,
|
||||
newsId: newsId,
|
||||
title: title,
|
||||
image: image,
|
||||
conTypeId: conTypeId,
|
||||
conType: conType,
|
||||
langId: langId,
|
||||
catId: catId,
|
||||
videoUpload: videoUpload,
|
||||
url: url,
|
||||
tagId: tagId,
|
||||
otherImage: otherImage,
|
||||
desc: desc,
|
||||
showTill: showTill,
|
||||
subCatId: subCatId,
|
||||
locationId: locationId,
|
||||
metaTitle: metaTitle,
|
||||
metaDescription: metaDescription,
|
||||
metaKeyword: metaKeyword,
|
||||
slug: slug,
|
||||
publishDate: publishDate ?? null,
|
||||
summDescription: summDescription,
|
||||
isDraft: isDraft);
|
||||
emit(AddNewsFetchSuccess(addNews: result));
|
||||
} catch (e) {
|
||||
emit(AddNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
98
news-app/lib/cubits/Auth/authCubit.dart
Normal file
98
news-app/lib/cubits/Auth/authCubit.dart
Normal file
@@ -0,0 +1,98 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/AuthModel.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
|
||||
const String loginEmail = "email";
|
||||
const String loginGmail = "gmail";
|
||||
const String loginFb = "fb";
|
||||
const String loginMbl = "mobile";
|
||||
const String loginApple = "apple";
|
||||
|
||||
enum AuthProviders { gmail, fb, apple, mobile, email }
|
||||
|
||||
@immutable
|
||||
abstract class AuthState {}
|
||||
|
||||
class AuthInitial extends AuthState {}
|
||||
|
||||
class Authenticated extends AuthState {
|
||||
//to store authDetails
|
||||
final AuthModel authModel;
|
||||
|
||||
Authenticated({required this.authModel});
|
||||
}
|
||||
|
||||
class Unauthenticated extends AuthState {}
|
||||
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final AuthRepository _authRepository;
|
||||
|
||||
AuthCubit(this._authRepository) : super(AuthInitial()) {
|
||||
checkAuthStatus();
|
||||
}
|
||||
|
||||
AuthRepository get authRepository => _authRepository;
|
||||
|
||||
void checkAuthStatus() {
|
||||
//authDetails is map. keys are isLogin,userId,authProvider
|
||||
final authDetails = _authRepository.getLocalAuthDetails();
|
||||
|
||||
(authDetails['isLogIn']) ? emit(Authenticated(authModel: AuthModel.fromJson(authDetails))) : emit(Unauthenticated());
|
||||
}
|
||||
|
||||
String getUserId() {
|
||||
return (state is Authenticated) ? (state as Authenticated).authModel.id! : "0";
|
||||
}
|
||||
|
||||
String getProfile() {
|
||||
return (state is Authenticated)
|
||||
? ((state as Authenticated).authModel.profile!.trim().isNotEmpty)
|
||||
? (state as Authenticated).authModel.profile!
|
||||
: ""
|
||||
: "";
|
||||
}
|
||||
|
||||
String getMobile() {
|
||||
return (state is Authenticated) ? (state as Authenticated).authModel.mobile! : "";
|
||||
}
|
||||
|
||||
String getType() {
|
||||
return (state is Authenticated) ? (state as Authenticated).authModel.type! : "";
|
||||
}
|
||||
|
||||
String getAuthorBio() {
|
||||
return (state is Authenticated && (state as Authenticated).authModel.authorDetails != null) ? ((state as Authenticated).authModel.authorDetails?.bio ?? "") : "";
|
||||
}
|
||||
|
||||
String getAuthorWhatsappLink() {
|
||||
return (state is Authenticated && (state as Authenticated).authModel.authorDetails != null) ? (state as Authenticated).authModel.authorDetails?.whatsappLink ?? "" : "0";
|
||||
}
|
||||
|
||||
String getAuthorTelegramLink() {
|
||||
return (state is Authenticated && (state as Authenticated).authModel.authorDetails != null) ? (state as Authenticated).authModel.authorDetails?.telegramLink ?? "" : "0";
|
||||
}
|
||||
|
||||
String getAuthorFacebookLink() {
|
||||
return (state is Authenticated && (state as Authenticated).authModel.authorDetails != null) ? (state as Authenticated).authModel.authorDetails?.facebookLink ?? "" : "0";
|
||||
}
|
||||
|
||||
String getAuthorLinkedInLink() {
|
||||
return (state is Authenticated && (state as Authenticated).authModel.authorDetails != null) ? (state as Authenticated).authModel.authorDetails?.linkedinLink ?? "" : "0";
|
||||
}
|
||||
|
||||
void updateDetails({required AuthModel authModel}) {
|
||||
emit(Authenticated(authModel: authModel));
|
||||
}
|
||||
|
||||
Future signOut(AuthProviders authProvider) async {
|
||||
if (state is Authenticated) {
|
||||
_authRepository.signOut(authProvider);
|
||||
emit(Unauthenticated());
|
||||
}
|
||||
}
|
||||
|
||||
bool isAuthor() {
|
||||
return (state is Authenticated) ? ((state as Authenticated).authModel.isAuthor == 1) : false;
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/Auth/deleteUserCubit.dart
Normal file
37
news-app/lib/cubits/Auth/deleteUserCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
|
||||
abstract class DeleteUserState {}
|
||||
|
||||
class DeleteUserInitial extends DeleteUserState {}
|
||||
|
||||
class DeleteUserFetchInProgress extends DeleteUserState {}
|
||||
|
||||
class DeleteUserFetchSuccess extends DeleteUserState {
|
||||
dynamic deleteUser;
|
||||
|
||||
DeleteUserFetchSuccess({required this.deleteUser});
|
||||
}
|
||||
|
||||
class DeleteUserFetchFailure extends DeleteUserState {
|
||||
final String errorMessage;
|
||||
|
||||
DeleteUserFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class DeleteUserCubit extends Cubit<DeleteUserState> {
|
||||
final AuthRepository _deleteUserRepository;
|
||||
|
||||
DeleteUserCubit(this._deleteUserRepository) : super(DeleteUserInitial());
|
||||
|
||||
Future<dynamic> deleteUser({String? name, String? mobile, String? email, String? filePath}) async {
|
||||
try {
|
||||
emit(DeleteUserFetchInProgress());
|
||||
final result = await _deleteUserRepository.deleteUser();
|
||||
emit(DeleteUserFetchSuccess(deleteUser: result));
|
||||
return result;
|
||||
} catch (e) {
|
||||
emit(DeleteUserFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/Auth/registerTokenCubit.dart
Normal file
37
news-app/lib/cubits/Auth/registerTokenCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
|
||||
@immutable
|
||||
abstract class RegisterTokenState {}
|
||||
|
||||
class RegisterTokenInitial extends RegisterTokenState {}
|
||||
|
||||
class RegisterTokenProgress extends RegisterTokenState {
|
||||
RegisterTokenProgress();
|
||||
}
|
||||
|
||||
class RegisterTokenSuccess extends RegisterTokenState {
|
||||
RegisterTokenSuccess();
|
||||
}
|
||||
|
||||
class RegisterTokenFailure extends RegisterTokenState {
|
||||
final String errorMessage;
|
||||
|
||||
RegisterTokenFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class RegisterTokenCubit extends Cubit<RegisterTokenState> {
|
||||
final AuthRepository _authRepository;
|
||||
|
||||
RegisterTokenCubit(this._authRepository) : super(RegisterTokenInitial());
|
||||
|
||||
void registerToken({required String fcmId, required BuildContext context}) {
|
||||
emit(RegisterTokenProgress());
|
||||
_authRepository.registerToken(fcmId: fcmId, context: context).then((result) {
|
||||
emit(RegisterTokenSuccess());
|
||||
}).catchError((e) {
|
||||
emit(RegisterTokenFailure(e.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
40
news-app/lib/cubits/Auth/socialSignUpCubit.dart
Normal file
40
news-app/lib/cubits/Auth/socialSignUpCubit.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
import 'package:news/data/models/AuthModel.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
import 'package:news/cubits/Auth/authCubit.dart';
|
||||
|
||||
@immutable
|
||||
abstract class SocialSignUpState {}
|
||||
|
||||
class SocialSignUpInitial extends SocialSignUpState {}
|
||||
|
||||
class SocialSignUpProgress extends SocialSignUpState {}
|
||||
|
||||
class SocialSignUpSuccess extends SocialSignUpState {
|
||||
final AuthModel authModel;
|
||||
|
||||
SocialSignUpSuccess({required this.authModel});
|
||||
}
|
||||
|
||||
class SocialSignUpFailure extends SocialSignUpState {
|
||||
final String errorMessage;
|
||||
|
||||
SocialSignUpFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SocialSignUpCubit extends Cubit<SocialSignUpState> {
|
||||
final AuthRepository _authRepository;
|
||||
|
||||
SocialSignUpCubit(this._authRepository) : super(SocialSignUpInitial());
|
||||
|
||||
void socialSignUpUser({required AuthProviders authProvider, required BuildContext context, String? email, String? password, String? otp, String? verifiedId}) {
|
||||
emit(SocialSignUpProgress());
|
||||
_authRepository.signInUser(email: email, otp: otp, password: password, verifiedId: verifiedId, authProvider: authProvider, context: context).then((result) {
|
||||
emit(SocialSignUpSuccess(authModel: AuthModel.fromJson(result[DATA])));
|
||||
}).catchError((e) {
|
||||
emit(SocialSignUpFailure(e.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
61
news-app/lib/cubits/Auth/updateUserCubit.dart
Normal file
61
news-app/lib/cubits/Auth/updateUserCubit.dart
Normal file
@@ -0,0 +1,61 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/cubits/Auth/authCubit.dart';
|
||||
import 'package:news/data/models/AuthModel.dart';
|
||||
import 'package:news/data/repositories/Auth/authRepository.dart';
|
||||
|
||||
abstract class UpdateUserState {}
|
||||
|
||||
class UpdateUserInitial extends UpdateUserState {}
|
||||
|
||||
class UpdateUserFetchInProgress extends UpdateUserState {}
|
||||
|
||||
class UpdateUserFetchSuccess extends UpdateUserState {
|
||||
AuthModel? updatedUser;
|
||||
String? imgUpdatedPath;
|
||||
|
||||
UpdateUserFetchSuccess({this.updatedUser, this.imgUpdatedPath});
|
||||
}
|
||||
|
||||
class UpdateUserFetchFailure extends UpdateUserState {
|
||||
final String errorMessage;
|
||||
|
||||
UpdateUserFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class UpdateUserCubit extends Cubit<UpdateUserState> {
|
||||
final AuthRepository _updateUserRepository;
|
||||
|
||||
UpdateUserCubit(this._updateUserRepository) : super(UpdateUserInitial());
|
||||
|
||||
void setUpdateUser(
|
||||
{String? name,
|
||||
String? mobile,
|
||||
String? email,
|
||||
String? filePath,
|
||||
required BuildContext context,
|
||||
String? authorBio,
|
||||
String? whatsappLink,
|
||||
String? facebookLink,
|
||||
String? telegramLink,
|
||||
String? linkedInLink}) async {
|
||||
try {
|
||||
emit(UpdateUserFetchInProgress());
|
||||
final Map<String, dynamic> result = await _updateUserRepository.updateUserData(
|
||||
mobile: mobile,
|
||||
name: name,
|
||||
email: email,
|
||||
filePath: filePath,
|
||||
authorBio: authorBio,
|
||||
whatsappLink: whatsappLink,
|
||||
facebookLink: facebookLink,
|
||||
telegramLink: telegramLink,
|
||||
linkedInLink: linkedInLink);
|
||||
//only incase of name,mobile & mail, not Profile Picture
|
||||
context.read<AuthCubit>().updateDetails(authModel: AuthModel.fromJson(result["data"]));
|
||||
emit(UpdateUserFetchSuccess(updatedUser: AuthModel.fromJson(result["data"])));
|
||||
} catch (e) {
|
||||
emit(UpdateUserFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
43
news-app/lib/cubits/Author/authorCubit.dart
Normal file
43
news-app/lib/cubits/Author/authorCubit.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class AuthorState {}
|
||||
|
||||
class AuthorInitial extends AuthorState {}
|
||||
|
||||
class AuthorInProgress extends AuthorState {}
|
||||
|
||||
class AuthorApproved extends AuthorState {
|
||||
AuthorApproved();
|
||||
}
|
||||
|
||||
class AuthorRequestSent extends AuthorState {
|
||||
final String responseMessage;
|
||||
AuthorRequestSent(this.responseMessage);
|
||||
}
|
||||
|
||||
class AuthorPending extends AuthorState {
|
||||
final String errorMessage;
|
||||
|
||||
AuthorPending(this.errorMessage);
|
||||
}
|
||||
|
||||
class AuthorRejected extends AuthorState {
|
||||
final String errorMessage;
|
||||
|
||||
AuthorRejected(this.errorMessage);
|
||||
}
|
||||
|
||||
class AuthorCubit extends Cubit<AuthorState> {
|
||||
AuthorCubit() : super(AuthorInitial());
|
||||
|
||||
void requestToBecomeAuthor() async {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(body: {}, url: Api.becomeAnAuthorApi);
|
||||
(!result[ERROR]) ? emit(AuthorRequestSent(result[MESSAGE])) : emit(AuthorPending(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(AuthorPending(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
49
news-app/lib/cubits/Author/authorNewsCubit.dart
Normal file
49
news-app/lib/cubits/Author/authorNewsCubit.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class AuthorNewsState {}
|
||||
|
||||
class AuthorNewsInitial extends AuthorNewsState {}
|
||||
|
||||
class AuthorNewsFetchInProgress extends AuthorNewsState {}
|
||||
|
||||
class AuthorNewsFetchSuccess extends AuthorNewsState {
|
||||
final List<NewsModel> AuthorNewsList;
|
||||
final UserAuthorModel authorData;
|
||||
final int totalAuthorNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
AuthorNewsFetchSuccess({required this.AuthorNewsList, required this.authorData, required this.totalAuthorNewsCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class AuthorNewsFetchFailed extends AuthorNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
AuthorNewsFetchFailed(this.errorMessage);
|
||||
}
|
||||
|
||||
class AuthorNewsCubit extends Cubit<AuthorNewsState> {
|
||||
AuthorNewsCubit() : super(AuthorNewsInitial());
|
||||
|
||||
void getAuthorNews({required String authorId}) async {
|
||||
try {
|
||||
emit(AuthorNewsInitial());
|
||||
final apiUrl = "${Api.getAuthorNewsApi}/${authorId}";
|
||||
final result = await Api.sendApiRequest(body: null, url: apiUrl, isGet: true);
|
||||
|
||||
(!result[ERROR])
|
||||
? emit(AuthorNewsFetchSuccess(
|
||||
AuthorNewsList: (result[DATA][NEWS][DATA] as List).map((e) => NewsModel.fromJson(e)).toList(),
|
||||
authorData: UserAuthorModel.fromJson(result[DATA][USER]),
|
||||
totalAuthorNewsCount: result[DATA][NEWS][TOTAL],
|
||||
hasMore: false,
|
||||
hasMoreFetchError: false))
|
||||
: emit(AuthorNewsFetchFailed(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(AuthorNewsFetchFailed(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
38
news-app/lib/cubits/Bookmark/UpdateBookmarkCubit.dart
Normal file
38
news-app/lib/cubits/Bookmark/UpdateBookmarkCubit.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/Bookmark/bookmarkRepository.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
abstract class UpdateBookmarkStatusState {}
|
||||
|
||||
class UpdateBookmarkStatusInitial extends UpdateBookmarkStatusState {}
|
||||
|
||||
class UpdateBookmarkStatusInProgress extends UpdateBookmarkStatusState {}
|
||||
|
||||
class UpdateBookmarkStatusSuccess extends UpdateBookmarkStatusState {
|
||||
final NewsModel news;
|
||||
final bool wasBookmarkNewsProcess; //to check that process of Bookmark done or not
|
||||
UpdateBookmarkStatusSuccess(this.news, this.wasBookmarkNewsProcess);
|
||||
}
|
||||
|
||||
class UpdateBookmarkStatusFailure extends UpdateBookmarkStatusState {
|
||||
final String errorMessage;
|
||||
|
||||
UpdateBookmarkStatusFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class UpdateBookmarkStatusCubit extends Cubit<UpdateBookmarkStatusState> {
|
||||
final BookmarkRepository bookmarkRepository;
|
||||
|
||||
UpdateBookmarkStatusCubit(this.bookmarkRepository) : super(UpdateBookmarkStatusInitial());
|
||||
|
||||
void setBookmarkNews({required NewsModel news, required String status}) {
|
||||
emit(UpdateBookmarkStatusInProgress());
|
||||
bookmarkRepository.setBookmark(newsId: (news.newsId != null) ? news.newsId! : news.id!, status: status).then((value) {
|
||||
emit(UpdateBookmarkStatusSuccess(news, status == "1" ? true : false));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(UpdateBookmarkStatusFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
111
news-app/lib/cubits/Bookmark/bookmarkCubit.dart
Normal file
111
news-app/lib/cubits/Bookmark/bookmarkCubit.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/Bookmark/bookmarkRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class BookmarkState {}
|
||||
|
||||
class BookmarkInitial extends BookmarkState {}
|
||||
|
||||
class BookmarkFetchInProgress extends BookmarkState {}
|
||||
|
||||
class BookmarkFetchSuccess extends BookmarkState {
|
||||
final List<NewsModel> bookmark;
|
||||
final int totalBookmarkCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
BookmarkFetchSuccess({required this.bookmark, required this.totalBookmarkCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class BookmarkFetchFailure extends BookmarkState {
|
||||
final String errorMessage;
|
||||
|
||||
BookmarkFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class BookmarkCubit extends Cubit<BookmarkState> {
|
||||
final BookmarkRepository bookmarkRepository;
|
||||
int perPageLimit = 25;
|
||||
|
||||
BookmarkCubit(this.bookmarkRepository) : super(BookmarkInitial());
|
||||
|
||||
void getBookmark({required String langId}) async {
|
||||
emit(BookmarkFetchInProgress());
|
||||
|
||||
try {
|
||||
final result = await bookmarkRepository.getBookmark(limit: perPageLimit.toString(), offset: "0", langId: langId);
|
||||
|
||||
if (result[ERROR]) {
|
||||
final message = result[MESSAGE];
|
||||
if (message == "No Data Found") {
|
||||
emit(BookmarkFetchSuccess(bookmark: [], totalBookmarkCount: 0, hasMoreFetchError: false, hasMore: false));
|
||||
} else {
|
||||
emit(BookmarkFetchFailure(message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final bookmarks = result['Bookmark'] as List<NewsModel>;
|
||||
final total = result[TOTAL] as int;
|
||||
|
||||
emit(BookmarkFetchSuccess(bookmark: bookmarks, totalBookmarkCount: total, hasMoreFetchError: false, hasMore: bookmarks.length < total));
|
||||
} catch (e) {
|
||||
final error = e.toString();
|
||||
emit(error == "No Data Found" ? BookmarkFetchSuccess(bookmark: [], totalBookmarkCount: 0, hasMoreFetchError: false, hasMore: false) : BookmarkFetchFailure(error));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreBookmark() {
|
||||
return (state is BookmarkFetchSuccess) ? (state as BookmarkFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreBookmark({required String langId}) async {
|
||||
if (state is BookmarkFetchSuccess) {
|
||||
try {
|
||||
final result = await bookmarkRepository.getBookmark(limit: perPageLimit.toString(), offset: (state as BookmarkFetchSuccess).bookmark.length.toString(), langId: langId);
|
||||
List<NewsModel> updatedResults = (state as BookmarkFetchSuccess).bookmark;
|
||||
updatedResults.addAll(result['Bookmark'] as List<NewsModel>);
|
||||
emit(BookmarkFetchSuccess(bookmark: updatedResults, totalBookmarkCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(BookmarkFetchSuccess(
|
||||
bookmark: (state as BookmarkFetchSuccess).bookmark,
|
||||
hasMoreFetchError: (e.toString() == "No Data Found") ? false : true,
|
||||
totalBookmarkCount: (state as BookmarkFetchSuccess).totalBookmarkCount,
|
||||
hasMore: (state as BookmarkFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void addBookmarkNews(NewsModel model) {
|
||||
if (state is BookmarkFetchSuccess) {
|
||||
List<NewsModel> bookmarklist = [];
|
||||
bookmarklist.insert(0, model);
|
||||
bookmarklist.addAll((state as BookmarkFetchSuccess).bookmark);
|
||||
|
||||
emit(BookmarkFetchSuccess(
|
||||
bookmark: List.from(bookmarklist), hasMoreFetchError: true, totalBookmarkCount: (state as BookmarkFetchSuccess).totalBookmarkCount, hasMore: (state as BookmarkFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
|
||||
void removeBookmarkNews(NewsModel model) {
|
||||
if (state is BookmarkFetchSuccess) {
|
||||
final bookmark = (state as BookmarkFetchSuccess).bookmark;
|
||||
bookmark.removeWhere(((element) => (element.id == model.id || element.newsId == model.id)));
|
||||
emit(BookmarkFetchSuccess(
|
||||
bookmark: List.from(bookmark), hasMoreFetchError: true, totalBookmarkCount: (state as BookmarkFetchSuccess).totalBookmarkCount, hasMore: (state as BookmarkFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
|
||||
bool isNewsBookmark(String newsId) {
|
||||
if (state is BookmarkFetchSuccess) {
|
||||
final bookmark = (state as BookmarkFetchSuccess).bookmark;
|
||||
return (bookmark.isNotEmpty) ? (bookmark.indexWhere((element) => (element.newsId == newsId || element.id == newsId)) != -1) : false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void resetState() {
|
||||
emit(BookmarkFetchInProgress());
|
||||
}
|
||||
}
|
||||
79
news-app/lib/cubits/ConnectivityCubit.dart
Normal file
79
news-app/lib/cubits/ConnectivityCubit.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:connectivity_plus/connectivity_plus.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
class ConnectivityCubit extends Cubit<ConnectivityState> {
|
||||
final ConnectivityService _connectivityService;
|
||||
late StreamSubscription _subscription;
|
||||
|
||||
ConnectivityCubit(this._connectivityService) : super(ConnectivityInitial()) {
|
||||
_startMonitoring();
|
||||
}
|
||||
|
||||
void _startMonitoring() {
|
||||
_subscription = _connectivityService.connectivityStream.listen((result) {
|
||||
if (result == ConnectivityResult.none) {
|
||||
emit(ConnectivityDisconnected());
|
||||
} else {
|
||||
emit(ConnectivityConnected(result));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> checkInitialConnection() async {
|
||||
final result = await _connectivityService.checkConnectivity();
|
||||
if (result == ConnectivityResult.none) {
|
||||
emit(ConnectivityDisconnected());
|
||||
} else {
|
||||
emit(ConnectivityConnected(result as ConnectivityResult));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_subscription.cancel();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class ConnectivityState extends Equatable {
|
||||
const ConnectivityState();
|
||||
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class ConnectivityInitial extends ConnectivityState {}
|
||||
|
||||
class ConnectivityConnected extends ConnectivityState {
|
||||
final ConnectivityResult result;
|
||||
|
||||
const ConnectivityConnected(this.result);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [result];
|
||||
}
|
||||
|
||||
class ConnectivityDisconnected extends ConnectivityState {}
|
||||
|
||||
class ConnectivityService {
|
||||
static final ConnectivityService _instance = ConnectivityService._internal();
|
||||
final Connectivity _connectivity = Connectivity();
|
||||
final StreamController<ConnectivityResult> _controller = StreamController<ConnectivityResult>.broadcast();
|
||||
|
||||
factory ConnectivityService() => _instance;
|
||||
|
||||
ConnectivityService._internal() {
|
||||
_connectivity.onConnectivityChanged.listen((result) {
|
||||
_controller.add(result.first); // Notify all listeners
|
||||
});
|
||||
}
|
||||
|
||||
Stream<ConnectivityResult> get connectivityStream => _controller.stream;
|
||||
|
||||
Future<List<ConnectivityResult>> checkConnectivity() async {
|
||||
return await _connectivity.checkConnectivity();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/LikeAndDisLikeNews/LikeAndDisLikeNewsRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class LikeAndDisLikeState {}
|
||||
|
||||
class LikeAndDisLikeInitial extends LikeAndDisLikeState {}
|
||||
|
||||
class LikeAndDisLikeFetchInProgress extends LikeAndDisLikeState {}
|
||||
|
||||
class LikeAndDisLikeFetchSuccess extends LikeAndDisLikeState {
|
||||
final List<NewsModel> likeAndDisLike;
|
||||
final int totalLikeAndDisLikeCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
LikeAndDisLikeFetchSuccess({required this.likeAndDisLike, required this.totalLikeAndDisLikeCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class LikeAndDisLikeFetchFailure extends LikeAndDisLikeState {
|
||||
final String errorMessage;
|
||||
|
||||
LikeAndDisLikeFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LikeAndDisLikeCubit extends Cubit<LikeAndDisLikeState> {
|
||||
final LikeAndDisLikeRepository likeAndDisLikeRepository;
|
||||
int perPageLimit = 25;
|
||||
|
||||
LikeAndDisLikeCubit(this.likeAndDisLikeRepository) : super(LikeAndDisLikeInitial());
|
||||
|
||||
void getLike({required String langId}) async {
|
||||
try {
|
||||
emit(LikeAndDisLikeFetchInProgress());
|
||||
final result = await likeAndDisLikeRepository.getLike(limit: perPageLimit.toString(), offset: "0", langId: langId);
|
||||
emit(LikeAndDisLikeFetchSuccess(
|
||||
likeAndDisLike: result['LikeAndDisLike'], totalLikeAndDisLikeCount: result[TOTAL], hasMoreFetchError: false, hasMore: (result['LikeAndDisLike'] as List<NewsModel>).length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(LikeAndDisLikeFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool isNewsLikeAndDisLike(String newsId) {
|
||||
if (state is LikeAndDisLikeFetchSuccess) {
|
||||
final likeAndDisLike = (state as LikeAndDisLikeFetchSuccess).likeAndDisLike;
|
||||
return likeAndDisLike.indexWhere((element) => (element.id == newsId || element.newsId == newsId)) != -1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void resetState() {
|
||||
emit(LikeAndDisLikeFetchInProgress());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import 'package:news/data/repositories/LikeAndDisLikeNews/LikeAndDisLikeNewsRepository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
abstract class UpdateLikeAndDisLikeStatusState {}
|
||||
|
||||
class UpdateLikeAndDisLikeStatusInitial extends UpdateLikeAndDisLikeStatusState {}
|
||||
|
||||
class UpdateLikeAndDisLikeStatusInProgress extends UpdateLikeAndDisLikeStatusState {}
|
||||
|
||||
class UpdateLikeAndDisLikeStatusSuccess extends UpdateLikeAndDisLikeStatusState {
|
||||
final NewsModel news;
|
||||
final bool wasLikeAndDisLikeNewsProcess; //to check that process of favorite done or not
|
||||
UpdateLikeAndDisLikeStatusSuccess(this.news, this.wasLikeAndDisLikeNewsProcess);
|
||||
}
|
||||
|
||||
class UpdateLikeAndDisLikeStatusFailure extends UpdateLikeAndDisLikeStatusState {
|
||||
final String errorMessage;
|
||||
|
||||
UpdateLikeAndDisLikeStatusFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class UpdateLikeAndDisLikeStatusCubit extends Cubit<UpdateLikeAndDisLikeStatusState> {
|
||||
final LikeAndDisLikeRepository likeAndDisLikeRepository;
|
||||
|
||||
UpdateLikeAndDisLikeStatusCubit(this.likeAndDisLikeRepository) : super(UpdateLikeAndDisLikeStatusInitial());
|
||||
|
||||
void setLikeAndDisLikeNews({required NewsModel news, required String status}) {
|
||||
emit(UpdateLikeAndDisLikeStatusInProgress());
|
||||
likeAndDisLikeRepository.setLike(newsId: (news.newsId != null) ? news.newsId! : news.id!, status: status).then((value) {
|
||||
emit(UpdateLikeAndDisLikeStatusSuccess(news, status == "1" ? true : false));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(UpdateLikeAndDisLikeStatusFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
39
news-app/lib/cubits/NewsByIdCubit.dart
Normal file
39
news-app/lib/cubits/NewsByIdCubit.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/NewsById/NewsByIdRepository.dart';
|
||||
|
||||
abstract class NewsByIdState {}
|
||||
|
||||
class NewsByIdInitial extends NewsByIdState {}
|
||||
|
||||
class NewsByIdFetchInProgress extends NewsByIdState {}
|
||||
|
||||
class NewsByIdFetchSuccess extends NewsByIdState {
|
||||
final List<NewsModel> newsById;
|
||||
|
||||
NewsByIdFetchSuccess({required this.newsById});
|
||||
}
|
||||
|
||||
class NewsByIdFetchFailure extends NewsByIdState {
|
||||
final String errorMessage;
|
||||
|
||||
NewsByIdFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class NewsByIdCubit extends Cubit<NewsByIdState> {
|
||||
final NewsByIdRepository _newsByIdRepository;
|
||||
|
||||
NewsByIdCubit(this._newsByIdRepository) : super(NewsByIdInitial());
|
||||
|
||||
Future<List<NewsModel>> getNewsById({required String newsId, required String langId}) async {
|
||||
try {
|
||||
emit(NewsByIdFetchInProgress());
|
||||
final result = await _newsByIdRepository.getNewsById(langId: langId, newsId: newsId);
|
||||
emit(NewsByIdFetchSuccess(newsById: result['NewsById']));
|
||||
return result['NewsById'];
|
||||
} catch (e) {
|
||||
emit(NewsByIdFetchFailure(e.toString()));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/NewsComment/deleteCommentCubit.dart
Normal file
37
news-app/lib/cubits/NewsComment/deleteCommentCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/NewsComment/DeleteComment/deleteCommRepository.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
abstract class DeleteCommState {}
|
||||
|
||||
class DeleteCommInitial extends DeleteCommState {}
|
||||
|
||||
class DeleteCommInProgress extends DeleteCommState {}
|
||||
|
||||
class DeleteCommSuccess extends DeleteCommState {
|
||||
final String message;
|
||||
|
||||
DeleteCommSuccess(this.message);
|
||||
}
|
||||
|
||||
class DeleteCommFailure extends DeleteCommState {
|
||||
final String errorMessage;
|
||||
|
||||
DeleteCommFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class DeleteCommCubit extends Cubit<DeleteCommState> {
|
||||
final DeleteCommRepository _deleteCommRepository;
|
||||
|
||||
DeleteCommCubit(this._deleteCommRepository) : super(DeleteCommInitial());
|
||||
|
||||
void setDeleteComm({required String commId}) {
|
||||
emit(DeleteCommInProgress());
|
||||
_deleteCommRepository.setDeleteComm(commId: commId).then((value) {
|
||||
emit(DeleteCommSuccess(value["message"]));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(DeleteCommFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
36
news-app/lib/cubits/NewsComment/flagCommentCubit.dart
Normal file
36
news-app/lib/cubits/NewsComment/flagCommentCubit.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/NewsComment/FlagComment/flagCommRepository.dart';
|
||||
|
||||
abstract class SetFlagState {}
|
||||
|
||||
class SetFlagInitial extends SetFlagState {}
|
||||
|
||||
class SetFlagFetchInProgress extends SetFlagState {}
|
||||
|
||||
class SetFlagFetchSuccess extends SetFlagState {
|
||||
String message;
|
||||
|
||||
SetFlagFetchSuccess({required this.message});
|
||||
}
|
||||
|
||||
class SetFlagFetchFailure extends SetFlagState {
|
||||
final String errorMessage;
|
||||
|
||||
SetFlagFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SetFlagCubit extends Cubit<SetFlagState> {
|
||||
final SetFlagRepository _setFlagRepository;
|
||||
|
||||
SetFlagCubit(this._setFlagRepository) : super(SetFlagInitial());
|
||||
|
||||
void setFlag({required String commId, required String newsId, required String message}) async {
|
||||
try {
|
||||
emit(SetFlagFetchInProgress());
|
||||
final result = await _setFlagRepository.setFlag(message: message, newsId: newsId, commId: commId);
|
||||
emit(SetFlagFetchSuccess(message: result['message']));
|
||||
} catch (e) {
|
||||
emit(SetFlagFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
41
news-app/lib/cubits/NewsComment/likeAndDislikeCommCubit.dart
Normal file
41
news-app/lib/cubits/NewsComment/likeAndDislikeCommCubit.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/CommentModel.dart';
|
||||
import 'package:news/data/repositories/NewsComment/LikeAndDislikeComment/likeAndDislikeCommRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class LikeAndDislikeCommState {}
|
||||
|
||||
class LikeAndDislikeCommInitial extends LikeAndDislikeCommState {}
|
||||
|
||||
class LikeAndDislikeCommInProgress extends LikeAndDislikeCommState {}
|
||||
|
||||
class LikeAndDislikeCommSuccess extends LikeAndDislikeCommState {
|
||||
final CommentModel comment;
|
||||
final bool wasLikeAndDislikeCommNewsProcess;
|
||||
final bool fromLike;
|
||||
|
||||
LikeAndDislikeCommSuccess(this.comment, this.wasLikeAndDislikeCommNewsProcess, this.fromLike);
|
||||
}
|
||||
|
||||
class LikeAndDislikeCommFailure extends LikeAndDislikeCommState {
|
||||
final String errorMessage;
|
||||
|
||||
LikeAndDislikeCommFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LikeAndDislikeCommCubit extends Cubit<LikeAndDislikeCommState> {
|
||||
final LikeAndDislikeCommRepository _likeAndDislikeCommRepository;
|
||||
|
||||
LikeAndDislikeCommCubit(this._likeAndDislikeCommRepository) : super(LikeAndDislikeCommInitial());
|
||||
|
||||
void setLikeAndDislikeComm({required String langId, required String commId, required String status, required bool fromLike}) async {
|
||||
try {
|
||||
emit(LikeAndDislikeCommInProgress());
|
||||
final result = await _likeAndDislikeCommRepository.setLikeAndDislikeComm(langId: langId, commId: commId, status: status);
|
||||
|
||||
(!result[ERROR]) ? emit(LikeAndDislikeCommSuccess(result['updatedComment'], true, fromLike)) : emit(LikeAndDislikeCommFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(LikeAndDislikeCommFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
39
news-app/lib/cubits/NewsComment/setCommentCubit.dart
Normal file
39
news-app/lib/cubits/NewsComment/setCommentCubit.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/CommentModel.dart';
|
||||
import 'package:news/data/repositories/NewsComment/SetComment/setComRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SetCommentState {}
|
||||
|
||||
class SetCommentInitial extends SetCommentState {}
|
||||
|
||||
class SetCommentFetchInProgress extends SetCommentState {}
|
||||
|
||||
class SetCommentFetchSuccess extends SetCommentState {
|
||||
List<CommentModel> setComment;
|
||||
int total;
|
||||
|
||||
SetCommentFetchSuccess({required this.setComment, required this.total});
|
||||
}
|
||||
|
||||
class SetCommentFetchFailure extends SetCommentState {
|
||||
final String errorMessage;
|
||||
|
||||
SetCommentFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SetCommentCubit extends Cubit<SetCommentState> {
|
||||
final SetCommentRepository _setCommentRepository;
|
||||
|
||||
SetCommentCubit(this._setCommentRepository) : super(SetCommentInitial());
|
||||
|
||||
void setComment({required String parentId, required String newsId, required String message}) async {
|
||||
emit(SetCommentFetchInProgress());
|
||||
try {
|
||||
final result = await _setCommentRepository.setComment(message: message, newsId: newsId, parentId: parentId);
|
||||
emit(SetCommentFetchSuccess(setComment: result['SetComment'], total: result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(SetCommentFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/SetUserPreferenceCat/setUserPrefCatRepository.dart';
|
||||
|
||||
abstract class SetUserPrefCatState {}
|
||||
|
||||
class SetUserPrefCatInitial extends SetUserPrefCatState {}
|
||||
|
||||
class SetUserPrefCatFetchInProgress extends SetUserPrefCatState {}
|
||||
|
||||
class SetUserPrefCatFetchSuccess extends SetUserPrefCatState {
|
||||
var setUserPrefCat;
|
||||
|
||||
SetUserPrefCatFetchSuccess({required this.setUserPrefCat});
|
||||
}
|
||||
|
||||
class SetUserPrefCatFetchFailure extends SetUserPrefCatState {
|
||||
final String errorMessage;
|
||||
|
||||
SetUserPrefCatFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SetUserPrefCatCubit extends Cubit<SetUserPrefCatState> {
|
||||
final SetUserPrefCatRepository _setUserPrefCatRepository;
|
||||
|
||||
SetUserPrefCatCubit(this._setUserPrefCatRepository) : super(SetUserPrefCatInitial());
|
||||
|
||||
void setUserPrefCat({required String catId}) async {
|
||||
emit(SetUserPrefCatFetchInProgress());
|
||||
try {
|
||||
final result = await _setUserPrefCatRepository.setUserPrefCat(catId: catId);
|
||||
|
||||
emit(SetUserPrefCatFetchSuccess(setUserPrefCat: result['SetUserPrefCat']));
|
||||
} catch (e) {
|
||||
emit(SetUserPrefCatFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
36
news-app/lib/cubits/UserPreferences/userByCategoryCubit.dart
Normal file
36
news-app/lib/cubits/UserPreferences/userByCategoryCubit.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/UserByCategory/userByCatRepository.dart';
|
||||
|
||||
abstract class UserByCatState {}
|
||||
|
||||
class UserByCatInitial extends UserByCatState {}
|
||||
|
||||
class UserByCatFetchInProgress extends UserByCatState {}
|
||||
|
||||
class UserByCatFetchSuccess extends UserByCatState {
|
||||
var userByCat;
|
||||
|
||||
UserByCatFetchSuccess({required this.userByCat});
|
||||
}
|
||||
|
||||
class UserByCatFetchFailure extends UserByCatState {
|
||||
final String errorMessage;
|
||||
|
||||
UserByCatFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class UserByCatCubit extends Cubit<UserByCatState> {
|
||||
final UserByCatRepository _userByCatRepository;
|
||||
|
||||
UserByCatCubit(this._userByCatRepository) : super(UserByCatInitial());
|
||||
|
||||
void getUserById() async {
|
||||
emit(UserByCatFetchInProgress());
|
||||
try {
|
||||
final result = await _userByCatRepository.getUserById();
|
||||
emit(UserByCatFetchSuccess(userByCat: result['UserByCat']['user_category']));
|
||||
} catch (e) {
|
||||
emit(UserByCatFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
41
news-app/lib/cubits/adSpacesNewsDetailsCubit.dart
Normal file
41
news-app/lib/cubits/adSpacesNewsDetailsCubit.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/adSpaceModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class AdSpacesNewsDetailsState {}
|
||||
|
||||
class AdSpacesNewsDetailsInitial extends AdSpacesNewsDetailsState {}
|
||||
|
||||
class AdSpacesNewsDetailsFetchInProgress extends AdSpacesNewsDetailsState {}
|
||||
|
||||
class AdSpacesNewsDetailsFetchSuccess extends AdSpacesNewsDetailsState {
|
||||
final AdSpaceModel? adSpaceTopData;
|
||||
final AdSpaceModel? adSpaceBottomData;
|
||||
|
||||
AdSpacesNewsDetailsFetchSuccess({this.adSpaceTopData, this.adSpaceBottomData});
|
||||
}
|
||||
|
||||
class AdSpacesNewsDetailsFetchFailure extends AdSpacesNewsDetailsState {
|
||||
final String errorMessage;
|
||||
|
||||
AdSpacesNewsDetailsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class AdSpacesNewsDetailsCubit extends Cubit<AdSpacesNewsDetailsState> {
|
||||
AdSpacesNewsDetailsCubit() : super(AdSpacesNewsDetailsInitial());
|
||||
|
||||
void getAdspaceForNewsDetails({required String langId}) async {
|
||||
emit(AdSpacesNewsDetailsFetchInProgress());
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId};
|
||||
final Map<String, dynamic> result = await Api.sendApiRequest(body: body, url: Api.getAdsNewsDetailsApi);
|
||||
final Map<String, dynamic> resultData = result[DATA];
|
||||
emit(AdSpacesNewsDetailsFetchSuccess(
|
||||
adSpaceTopData: (resultData.containsKey('ad_spaces_top')) ? (AdSpaceModel.fromJson(resultData['ad_spaces_top'])) : null,
|
||||
adSpaceBottomData: (resultData.containsKey('ad_spaces_bottom')) ? AdSpaceModel.fromJson(resultData['ad_spaces_bottom']) : null));
|
||||
} catch (e) {
|
||||
emit(AdSpacesNewsDetailsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
26
news-app/lib/cubits/appLocalizationCubit.dart
Normal file
26
news-app/lib/cubits/appLocalizationCubit.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/Settings/settingsLocalDataRepository.dart';
|
||||
|
||||
class AppLocalizationState {
|
||||
String languageCode;
|
||||
String id;
|
||||
int isRTL;
|
||||
|
||||
AppLocalizationState(
|
||||
this.languageCode,
|
||||
this.id,
|
||||
this.isRTL,
|
||||
);
|
||||
}
|
||||
|
||||
class AppLocalizationCubit extends Cubit<AppLocalizationState> {
|
||||
final SettingsLocalDataRepository _settingsRepository;
|
||||
|
||||
AppLocalizationCubit(this._settingsRepository)
|
||||
: super(AppLocalizationState(_settingsRepository.getCurrentLanguageCode(), _settingsRepository.getCurrentLanguageId(), _settingsRepository.getCurrentLanguageRTL()));
|
||||
|
||||
void changeLanguage(String lanCode, String lanId, int lanRTL) {
|
||||
_settingsRepository.setLanguagePreferences(code: lanCode, id: lanId, rtl: lanRTL);
|
||||
emit(AppLocalizationState(lanCode, lanId, lanRTL));
|
||||
}
|
||||
}
|
||||
254
news-app/lib/cubits/appSystemSettingCubit.dart
Normal file
254
news-app/lib/cubits/appSystemSettingCubit.dart
Normal file
@@ -0,0 +1,254 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/app/app.dart';
|
||||
import 'package:news/data/models/AppSystemSettingModel.dart';
|
||||
import 'package:news/data/repositories/AppSystemSetting/systemRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
|
||||
abstract class AppConfigurationState {}
|
||||
|
||||
class AppConfigurationInitial extends AppConfigurationState {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class AppConfigurationFetchInProgress extends AppConfigurationState {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class AppConfigurationFetchSuccess extends AppConfigurationState {
|
||||
final AppSystemSettingModel appConfiguration;
|
||||
|
||||
AppConfigurationFetchSuccess({required this.appConfiguration});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [appConfiguration];
|
||||
}
|
||||
|
||||
class AppConfigurationFetchFailure extends AppConfigurationState {
|
||||
final String errorMessage;
|
||||
|
||||
AppConfigurationFetchFailure(this.errorMessage);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [errorMessage];
|
||||
}
|
||||
|
||||
class AppConfigurationCubit extends Cubit<AppConfigurationState> {
|
||||
final SystemRepository _systemRepository;
|
||||
|
||||
AppConfigurationCubit(this._systemRepository) : super(AppConfigurationInitial());
|
||||
|
||||
fetchAppConfiguration() async {
|
||||
emit(AppConfigurationFetchInProgress());
|
||||
try {
|
||||
final appConfiguration = AppSystemSettingModel.fromJson(await _systemRepository.fetchSettings());
|
||||
emit(AppConfigurationFetchSuccess(appConfiguration: appConfiguration));
|
||||
} catch (e) {
|
||||
emit(AppConfigurationFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
AppSystemSettingModel getAppConfiguration() {
|
||||
return (state is AppConfigurationFetchSuccess) ? (state as AppConfigurationFetchSuccess).appConfiguration : AppSystemSettingModel.fromJson({});
|
||||
}
|
||||
|
||||
String? getBreakingNewsMode() {
|
||||
return ((state is AppConfigurationFetchSuccess)) ? getAppConfiguration().breakNewsMode : "";
|
||||
}
|
||||
|
||||
String? getLiveStreamMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().liveStreamMode : "";
|
||||
}
|
||||
|
||||
String? getCategoryMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().catMode : "";
|
||||
}
|
||||
|
||||
String? getSubCatMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().subCatMode : "";
|
||||
}
|
||||
|
||||
String? getCommentsMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().commentMode : "";
|
||||
}
|
||||
|
||||
String? getInAppAdsMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? ((Platform.isAndroid) ? getAppConfiguration().inAppAdsMode : getAppConfiguration().iosInAppAdsMode) : "";
|
||||
}
|
||||
|
||||
String? getLocationWiseNewsMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().locationWiseNewsMode : "";
|
||||
}
|
||||
|
||||
String? getWeatherMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().weatherMode : "";
|
||||
}
|
||||
|
||||
String? getMaintenanceMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().maintenanceMode : "0";
|
||||
}
|
||||
|
||||
String? checkAdsType() {
|
||||
if (getInAppAdsMode() == "1") {
|
||||
return (Platform.isIOS) ? getIOSAdsType() : getAdsType();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? getAdsType() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
switch (getAppConfiguration().adsType) {
|
||||
case "1":
|
||||
return "google";
|
||||
case "3":
|
||||
return "unity";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? getIOSAdsType() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
switch (getAppConfiguration().iosAdsType) {
|
||||
case "1":
|
||||
return "google";
|
||||
case "3":
|
||||
return "unity";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? bannerId() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
if (Platform.isAndroid && getInAppAdsMode() != "0") {
|
||||
if (getAdsType() == "google") return getAppConfiguration().goBannerId;
|
||||
if (getAdsType() == "unity") return getAppConfiguration().unityBannerId;
|
||||
}
|
||||
if (Platform.isIOS && getInAppAdsMode() != "0") {
|
||||
if (getIOSAdsType() == "google") return getAppConfiguration().goIOSBannerId;
|
||||
if (getIOSAdsType() == "unity") return getAppConfiguration().unityIOSBannerId;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? rewardId() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
if (Platform.isAndroid && getInAppAdsMode() != "0") {
|
||||
if (getAdsType() == "google") return getAppConfiguration().goRewardedId;
|
||||
if (getAdsType() == "unity") return getAppConfiguration().unityRewardedId;
|
||||
}
|
||||
if (Platform.isIOS && getInAppAdsMode() != "0") {
|
||||
if (getIOSAdsType() == "google") return getAppConfiguration().goIOSRewardedId;
|
||||
if (getIOSAdsType() == "unity") return getAppConfiguration().unityIOSRewardedId;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? nativeId() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
if (Platform.isAndroid && getInAppAdsMode() != "0") {
|
||||
if (getAdsType() == "google") return getAppConfiguration().goNativeId;
|
||||
if (getAdsType() == "unity") return ""; //no native ads in unity
|
||||
}
|
||||
if (Platform.isIOS && getInAppAdsMode() != "0") {
|
||||
if (getIOSAdsType() == "google") return getAppConfiguration().goIOSNativeId;
|
||||
if (getIOSAdsType() == "unity") return ""; //no native ads in unity
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? interstitialId() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
if (Platform.isAndroid && getInAppAdsMode() != "0") {
|
||||
if (getAdsType() == "google") return getAppConfiguration().goInterId;
|
||||
if (getAdsType() == "unity") return getAppConfiguration().unityInterId;
|
||||
}
|
||||
if (Platform.isIOS && getInAppAdsMode() != "0") {
|
||||
if (getIOSAdsType() == "google") return getAppConfiguration().goIOSInterId;
|
||||
if (getIOSAdsType() == "unity") return getAppConfiguration().unityIOSInterId;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String? unityGameId() {
|
||||
return (Platform.isAndroid) ? getAppConfiguration().gameId : getAppConfiguration().iosGameId;
|
||||
}
|
||||
|
||||
String? getRSSFeedMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().rssFeedMode : "";
|
||||
}
|
||||
|
||||
String? getMobileLoginMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().mobileLoginMode : "";
|
||||
}
|
||||
|
||||
String? getCountryCode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().countryCode : "IN"; //India bydefault
|
||||
}
|
||||
|
||||
String? getShareAppText() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().shareAppText : "";
|
||||
}
|
||||
|
||||
String? getAppstoreId() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().appstoreId : "";
|
||||
}
|
||||
|
||||
String? getiOSAppLink() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().iosAppLink : "";
|
||||
}
|
||||
|
||||
String? getAndroidAppLink() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().androidAppLink : "";
|
||||
}
|
||||
|
||||
VideoViewType? getVideoTypePreference() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().videoTypePreference : VideoViewType.normal;
|
||||
}
|
||||
|
||||
String? getForceUpdateMode() {
|
||||
return (state is AppConfigurationFetchSuccess) ? getAppConfiguration().forceUpdateMode : "";
|
||||
}
|
||||
|
||||
bool needsUpdate(String enforceVersion) {
|
||||
final List<int> currentVersion = packageInfo.version.split('.').map((String number) => int.parse(number)).toList();
|
||||
final List<int> enforcedVersion = enforceVersion.split('.').map((String number) => int.parse(number)).toList();
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
if (enforcedVersion[i] > currentVersion[i]) {
|
||||
return true;
|
||||
} else if (currentVersion[i] > enforcedVersion[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
String getGeminiAPiKey() {
|
||||
return ((state is AppConfigurationFetchSuccess)) ? UiUtils.decryptKey(geminiKey: getAppConfiguration().googleGeminiApiKey) : "";
|
||||
}
|
||||
|
||||
bool isUpdateRequired() {
|
||||
if (state is AppConfigurationFetchSuccess) {
|
||||
AppSystemSettingModel appConfig = (state as AppConfigurationFetchSuccess).appConfiguration;
|
||||
if (defaultTargetPlatform == TargetPlatform.android && needsUpdate(appConfig.androidAppVersion ?? "") ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS && needsUpdate(appConfig.iosAppVersion ?? "")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
40
news-app/lib/cubits/breakingNewsCubit.dart
Normal file
40
news-app/lib/cubits/breakingNewsCubit.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/BreakingNewsModel.dart';
|
||||
import 'package:news/data/repositories/BreakingNews/breakNewsRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class BreakingNewsState {}
|
||||
|
||||
class BreakingNewsInitial extends BreakingNewsState {}
|
||||
|
||||
class BreakingNewsFetchInProgress extends BreakingNewsState {}
|
||||
|
||||
class BreakingNewsFetchSuccess extends BreakingNewsState {
|
||||
final List<BreakingNewsModel> breakingNews;
|
||||
|
||||
BreakingNewsFetchSuccess({required this.breakingNews});
|
||||
}
|
||||
|
||||
class BreakingNewsFetchFailure extends BreakingNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
BreakingNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class BreakingNewsCubit extends Cubit<BreakingNewsState> {
|
||||
final BreakingNewsRepository _breakingNewsRepository;
|
||||
|
||||
BreakingNewsCubit(this._breakingNewsRepository) : super(BreakingNewsInitial());
|
||||
|
||||
Future<List<BreakingNewsModel>> getBreakingNews({required String langId}) async {
|
||||
emit(BreakingNewsFetchInProgress());
|
||||
try {
|
||||
final result = await _breakingNewsRepository.getBreakingNews(langId: langId);
|
||||
(!result[ERROR]) ? emit(BreakingNewsFetchSuccess(breakingNews: result['BreakingNews'])) : emit(BreakingNewsFetchFailure(result[MESSAGE]));
|
||||
return (!result[ERROR]) ? result['BreakingNews'] : [];
|
||||
} catch (e) {
|
||||
emit(BreakingNewsFetchFailure(e.toString()));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
112
news-app/lib/cubits/categoryCubit.dart
Normal file
112
news-app/lib/cubits/categoryCubit.dart
Normal file
@@ -0,0 +1,112 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/data/repositories/Category/categoryRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class CategoryState {}
|
||||
|
||||
class CategoryInitial extends CategoryState {}
|
||||
|
||||
class CategoryFetchInProgress extends CategoryState {}
|
||||
|
||||
class CategoryFetchSuccess extends CategoryState {
|
||||
final List<CategoryModel> category;
|
||||
final int totalCategoryCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
CategoryFetchSuccess(
|
||||
{required this.category,
|
||||
required this.totalCategoryCount,
|
||||
required this.hasMoreFetchError,
|
||||
required this.hasMore});
|
||||
}
|
||||
|
||||
class CategoryFetchFailure extends CategoryState {
|
||||
final String errorMessage;
|
||||
|
||||
CategoryFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class CategoryCubit extends Cubit<CategoryState> {
|
||||
final CategoryRepository _categoryRepository;
|
||||
|
||||
CategoryCubit(this._categoryRepository) : super(CategoryInitial());
|
||||
|
||||
void getCategory({required String langId}) async {
|
||||
try {
|
||||
emit(CategoryFetchInProgress());
|
||||
int catLimit = 20;
|
||||
final result = await _categoryRepository.getCategory(
|
||||
limit: catLimit.toString(), offset: "0", langId: langId);
|
||||
(!result[ERROR])
|
||||
? emit(CategoryFetchSuccess(
|
||||
category: result['Category'],
|
||||
totalCategoryCount: result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: (result['Category'] as List<CategoryModel>).length <
|
||||
result[TOTAL]))
|
||||
: emit(CategoryFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(CategoryFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
// Load categories if not already loaded or failed
|
||||
void loadIfFailed({required String langId}) {
|
||||
if (state is CategoryInitial || state is CategoryFetchFailure) {
|
||||
getCategory(langId: langId);
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreCategory() {
|
||||
return (state is CategoryFetchSuccess)
|
||||
? (state as CategoryFetchSuccess).hasMore
|
||||
: false;
|
||||
}
|
||||
|
||||
void getMoreCategory({required String langId}) async {
|
||||
if (state is CategoryFetchSuccess) {
|
||||
try {
|
||||
final result = await _categoryRepository.getCategory(
|
||||
limit: limitOfAPIData.toString(),
|
||||
langId: langId,
|
||||
offset: (state as CategoryFetchSuccess).category.length.toString());
|
||||
if (!result[ERROR]) {
|
||||
List<CategoryModel> updatedResults =
|
||||
(state as CategoryFetchSuccess).category;
|
||||
updatedResults.addAll(result['Category'] as List<CategoryModel>);
|
||||
emit(CategoryFetchSuccess(
|
||||
category: updatedResults,
|
||||
totalCategoryCount: result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: updatedResults.length < result[TOTAL]));
|
||||
} else {
|
||||
emit(CategoryFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(CategoryFetchSuccess(
|
||||
category: (state as CategoryFetchSuccess).category,
|
||||
hasMoreFetchError: true,
|
||||
totalCategoryCount:
|
||||
(state as CategoryFetchSuccess).totalCategoryCount,
|
||||
hasMore: (state as CategoryFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<CategoryModel> getCatList() {
|
||||
return (state is CategoryFetchSuccess)
|
||||
? (state as CategoryFetchSuccess).category
|
||||
: [];
|
||||
}
|
||||
|
||||
int getCategoryIndex({required String categoryName}) {
|
||||
return (state is CategoryFetchSuccess)
|
||||
? (state as CategoryFetchSuccess)
|
||||
.category
|
||||
.indexWhere((element) => element.categoryName == categoryName)
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
111
news-app/lib/cubits/commentNewsCubit.dart
Normal file
111
news-app/lib/cubits/commentNewsCubit.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/CommentModel.dart';
|
||||
import 'package:news/data/repositories/CommentNews/commNewsRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class CommentNewsState {}
|
||||
|
||||
class CommentNewsInitial extends CommentNewsState {}
|
||||
|
||||
class CommentNewsFetchInProgress extends CommentNewsState {}
|
||||
|
||||
class CommentNewsFetchSuccess extends CommentNewsState {
|
||||
final List<CommentModel> commentNews;
|
||||
final int totalCommentNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
CommentNewsFetchSuccess({required this.commentNews, required this.totalCommentNewsCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
CommentNewsFetchSuccess copyWith({List<CommentModel>? commentNews, int? totalCommentNewsCount, bool? hasMoreFetchError, bool? hasMore}) {
|
||||
return CommentNewsFetchSuccess(
|
||||
commentNews: commentNews ?? this.commentNews,
|
||||
totalCommentNewsCount: totalCommentNewsCount ?? this.totalCommentNewsCount,
|
||||
hasMoreFetchError: hasMoreFetchError ?? this.hasMoreFetchError,
|
||||
hasMore: hasMore ?? this.hasMore);
|
||||
}
|
||||
}
|
||||
|
||||
class CommentNewsFetchFailure extends CommentNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
CommentNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class CommentNewsCubit extends Cubit<CommentNewsState> {
|
||||
final CommentNewsRepository _commentNewsRepository;
|
||||
|
||||
CommentNewsCubit(this._commentNewsRepository) : super(CommentNewsInitial());
|
||||
|
||||
void getCommentNews({required String newsId}) async {
|
||||
try {
|
||||
emit(CommentNewsFetchInProgress());
|
||||
final result = await _commentNewsRepository.getCommentNews(limit: limitOfAPIData.toString(), offset: "0", newsId: newsId);
|
||||
|
||||
(!result[ERROR])
|
||||
? emit(CommentNewsFetchSuccess(
|
||||
commentNews: result['CommentNews'], totalCommentNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: ((result['CommentNews'] as List<CommentModel>).length) < result[TOTAL]))
|
||||
: emit(CommentNewsFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(CommentNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreCommentNews() {
|
||||
return (state is CommentNewsFetchSuccess) ? (state as CommentNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreCommentNews({required String newsId}) async {
|
||||
if (state is CommentNewsFetchSuccess) {
|
||||
try {
|
||||
final result = await _commentNewsRepository.getCommentNews(limit: limitOfAPIData.toString(), newsId: newsId, offset: (state as CommentNewsFetchSuccess).commentNews.length.toString());
|
||||
List<CommentModel> updatedResults = (state as CommentNewsFetchSuccess).commentNews;
|
||||
updatedResults.addAll(result['CommentNews'] as List<CommentModel>);
|
||||
emit(CommentNewsFetchSuccess(commentNews: updatedResults, totalCommentNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(CommentNewsFetchSuccess(
|
||||
commentNews: (state as CommentNewsFetchSuccess).commentNews,
|
||||
hasMoreFetchError: true,
|
||||
totalCommentNewsCount: (state as CommentNewsFetchSuccess).totalCommentNewsCount,
|
||||
hasMore: (state as CommentNewsFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emitSuccessState(List<CommentModel> commments) {
|
||||
emit((state as CommentNewsFetchSuccess).copyWith(commentNews: commments));
|
||||
}
|
||||
|
||||
void commentUpdateList(List<CommentModel> commentList, int total) {
|
||||
if (state is CommentNewsFetchSuccess || state is CommentNewsFetchFailure) {
|
||||
bool haseMore = (state is CommentNewsFetchSuccess) ? (state as CommentNewsFetchSuccess).hasMore : false;
|
||||
emit(CommentNewsFetchSuccess(commentNews: commentList, hasMore: haseMore, hasMoreFetchError: false, totalCommentNewsCount: total));
|
||||
}
|
||||
}
|
||||
|
||||
void deleteComment(int index) {
|
||||
if (state is CommentNewsFetchSuccess) {
|
||||
List<CommentModel> commentList = List.from((state as CommentNewsFetchSuccess).commentNews)..removeAt(index);
|
||||
|
||||
emit(CommentNewsFetchSuccess(
|
||||
commentNews: commentList,
|
||||
hasMore: (state as CommentNewsFetchSuccess).hasMore,
|
||||
hasMoreFetchError: false,
|
||||
totalCommentNewsCount: (state as CommentNewsFetchSuccess).totalCommentNewsCount - 1));
|
||||
}
|
||||
}
|
||||
|
||||
void deleteCommentReply(String commentId, int index) {
|
||||
if (state is CommentNewsFetchSuccess) {
|
||||
List<CommentModel> commentList = (state as CommentNewsFetchSuccess).commentNews;
|
||||
commentList.forEach((element) {
|
||||
if (element.id! == commentId) {
|
||||
int commIndex = commentList.indexWhere((model) => model.id == commentId);
|
||||
commentList[commIndex].replyComList!.removeAt(index);
|
||||
}
|
||||
});
|
||||
emit(CommentNewsFetchSuccess(
|
||||
commentNews: commentList, hasMore: (state as CommentNewsFetchSuccess).hasMore, hasMoreFetchError: false, totalCommentNewsCount: (state as CommentNewsFetchSuccess).totalCommentNewsCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/deleteImageId.dart
Normal file
37
news-app/lib/cubits/deleteImageId.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../data/repositories/DeleteImageId/deleteImageRepository.dart';
|
||||
import '../utils/api.dart';
|
||||
|
||||
abstract class DeleteImageState {}
|
||||
|
||||
class DeleteImageInitial extends DeleteImageState {}
|
||||
|
||||
class DeleteImageInProgress extends DeleteImageState {}
|
||||
|
||||
class DeleteImageSuccess extends DeleteImageState {
|
||||
final String message;
|
||||
|
||||
DeleteImageSuccess(this.message);
|
||||
}
|
||||
|
||||
class DeleteImageFailure extends DeleteImageState {
|
||||
final String errorMessage;
|
||||
|
||||
DeleteImageFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class DeleteImageCubit extends Cubit<DeleteImageState> {
|
||||
final DeleteImageRepository _deleteImageRepository;
|
||||
|
||||
DeleteImageCubit(this._deleteImageRepository) : super(DeleteImageInitial());
|
||||
|
||||
void setDeleteImage({required String imageId}) {
|
||||
emit(DeleteImageInProgress());
|
||||
_deleteImageRepository.setDeleteImage(imageId: imageId).then((value) {
|
||||
emit(DeleteImageSuccess(value["message"]));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(DeleteImageFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
44
news-app/lib/cubits/deleteUserNewsCubit.dart
Normal file
44
news-app/lib/cubits/deleteUserNewsCubit.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../data/repositories/DeleteUserNews/deleteUserNewsRepository.dart';
|
||||
import '../utils/api.dart';
|
||||
|
||||
abstract class DeleteUserNewsState {}
|
||||
|
||||
class DeleteUserNewsInitial extends DeleteUserNewsState {}
|
||||
|
||||
class DeleteUserNewsInProgress extends DeleteUserNewsState {}
|
||||
|
||||
class DeleteUserNewsSuccess extends DeleteUserNewsState {
|
||||
final String message;
|
||||
|
||||
DeleteUserNewsSuccess(this.message);
|
||||
}
|
||||
|
||||
class DeleteUserNewsFailure extends DeleteUserNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
DeleteUserNewsFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class DeleteUserNewsCubit extends Cubit<DeleteUserNewsState> {
|
||||
final DeleteUserNewsRepository _deleteUserNewsRepository;
|
||||
|
||||
DeleteUserNewsCubit(this._deleteUserNewsRepository) : super(DeleteUserNewsInitial());
|
||||
|
||||
void setDeleteUserNews({
|
||||
required String newsId,
|
||||
}) {
|
||||
emit(DeleteUserNewsInProgress());
|
||||
_deleteUserNewsRepository
|
||||
.setDeleteUserNews(
|
||||
newsId: newsId,
|
||||
)
|
||||
.then((value) {
|
||||
emit(DeleteUserNewsSuccess(value["message"]));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(DeleteUserNewsFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
71
news-app/lib/cubits/featureSectionCubit.dart
Normal file
71
news-app/lib/cubits/featureSectionCubit.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/FeatureSectionModel.dart';
|
||||
import 'package:news/data/repositories/FeatureSection/sectionRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SectionState {}
|
||||
|
||||
class SectionInitial extends SectionState {}
|
||||
|
||||
class SectionFetchInProgress extends SectionState {}
|
||||
|
||||
class SectionFetchSuccess extends SectionState {
|
||||
final List<FeatureSectionModel> section;
|
||||
final int totalCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
SectionFetchSuccess({required this.section, required this.totalCount, required this.hasMore, required this.hasMoreFetchError});
|
||||
}
|
||||
|
||||
class SectionFetchFailure extends SectionState {
|
||||
final String errorMessage;
|
||||
|
||||
SectionFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SectionCubit extends Cubit<SectionState> {
|
||||
final SectionRepository _sectionRepository;
|
||||
|
||||
SectionCubit(this._sectionRepository) : super(SectionInitial());
|
||||
|
||||
void getSection({required String langId, String? latitude, String? longitude}) async {
|
||||
try {
|
||||
emit(SectionFetchInProgress());
|
||||
final result = await _sectionRepository.getSection(langId: langId, latitude: latitude, longitude: longitude, limit: limitOfAPIData.toString(), offset: "0", sectionOffset: "0");
|
||||
(!result[ERROR])
|
||||
? emit(SectionFetchSuccess(
|
||||
section: result['Section'],
|
||||
totalCount: result[TOTAL],
|
||||
hasMore: result['Section'].length < result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
))
|
||||
: emit(SectionFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(SectionFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreSections() {
|
||||
return (state is SectionFetchSuccess) ? (state as SectionFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreSections({required String langId, String? latitude, String? longitude}) async {
|
||||
if (state is SectionFetchSuccess) {
|
||||
try {
|
||||
final result = await _sectionRepository.getSection(
|
||||
langId: langId, latitude: latitude, longitude: longitude, limit: limitOfAPIData.toString(), offset: "0", sectionOffset: (state as SectionFetchSuccess).section.length.toString());
|
||||
if (!result[ERROR]) {
|
||||
List<FeatureSectionModel> updatedResults = (state as SectionFetchSuccess).section;
|
||||
updatedResults.addAll(result['Section'] as List<FeatureSectionModel>);
|
||||
emit(SectionFetchSuccess(section: updatedResults, totalCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} else {
|
||||
emit(SectionFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(SectionFetchSuccess(
|
||||
section: (state as SectionFetchSuccess).section, hasMoreFetchError: true, totalCount: (state as SectionFetchSuccess).totalCount, hasMore: (state as SectionFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
77
news-app/lib/cubits/generalNewsCubit.dart
Normal file
77
news-app/lib/cubits/generalNewsCubit.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class GeneralNewsState {}
|
||||
|
||||
class GeneralNewsInitial extends GeneralNewsState {}
|
||||
|
||||
class GeneralNewsFetchInProgress extends GeneralNewsState {}
|
||||
|
||||
class GeneralNewsFetchSuccess extends GeneralNewsState {
|
||||
final List<NewsModel> generalNews;
|
||||
final int totalCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
GeneralNewsFetchSuccess({required this.totalCount, required this.hasMoreFetchError, required this.hasMore, required this.generalNews});
|
||||
}
|
||||
|
||||
class GeneralNewsFetchFailure extends GeneralNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
GeneralNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class GeneralNewsCubit extends Cubit<GeneralNewsState> {
|
||||
GeneralNewsCubit() : super(GeneralNewsInitial());
|
||||
|
||||
Future<dynamic> getGeneralNews({required String langId, String? latitude, String? longitude, int? offset, String? newsSlug}) async {
|
||||
emit(GeneralNewsInitial());
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId, LIMIT: 20};
|
||||
|
||||
if (latitude != null && latitude != "null") body[LATITUDE] = latitude;
|
||||
if (longitude != null && longitude != "null") body[LONGITUDE] = longitude;
|
||||
if (offset != null) body[OFFSET] = offset;
|
||||
if (newsSlug != null && newsSlug != "null" && newsSlug.trim().isNotEmpty) body[SLUG] = newsSlug; // used in case of native link , details screen redirection
|
||||
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getNewsApi);
|
||||
if (!result[ERROR]) {
|
||||
emit(GeneralNewsFetchSuccess(
|
||||
generalNews: (result[DATA] as List).map((e) => NewsModel.fromJson(e)).toList(), totalCount: result[TOTAL], hasMoreFetchError: false, hasMore: result[DATA].length < result[TOTAL]));
|
||||
} else {
|
||||
emit(GeneralNewsFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreGeneralNews() {
|
||||
return (state is GeneralNewsFetchSuccess) ? (state as GeneralNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreGeneralNews({required String langId, String? latitude, String? longitude}) async {
|
||||
if (state is GeneralNewsFetchSuccess) {
|
||||
try {
|
||||
final result = await getGeneralNews(langId: langId, latitude: latitude, longitude: longitude, offset: (state as GeneralNewsFetchSuccess).generalNews.length);
|
||||
if (!result[ERROR]) {
|
||||
List<NewsModel> updatedResults = (state as GeneralNewsFetchSuccess).generalNews;
|
||||
updatedResults.addAll((result[DATA] as List).map((e) => NewsModel.fromJson(e)).toList());
|
||||
emit(GeneralNewsFetchSuccess(generalNews: updatedResults, totalCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} else {
|
||||
emit(GeneralNewsFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(GeneralNewsFetchSuccess(
|
||||
generalNews: (state as GeneralNewsFetchSuccess).generalNews,
|
||||
hasMoreFetchError: true,
|
||||
totalCount: (state as GeneralNewsFetchSuccess).totalCount,
|
||||
hasMore: (state as GeneralNewsFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/getSurveyAnswerCubit.dart
Normal file
37
news-app/lib/cubits/getSurveyAnswerCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/GetSurveyAnswer/getSurveyAnsRepository.dart';
|
||||
|
||||
abstract class GetSurveyAnsState {}
|
||||
|
||||
class GetSurveyAnsInitial extends GetSurveyAnsState {}
|
||||
|
||||
class GetSurveyAnsFetchInProgress extends GetSurveyAnsState {}
|
||||
|
||||
class GetSurveyAnsFetchSuccess extends GetSurveyAnsState {
|
||||
final List<NewsModel> getSurveyAns;
|
||||
|
||||
GetSurveyAnsFetchSuccess({required this.getSurveyAns});
|
||||
}
|
||||
|
||||
class GetSurveyAnsFetchFailure extends GetSurveyAnsState {
|
||||
final String errorMessage;
|
||||
|
||||
GetSurveyAnsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class GetSurveyAnsCubit extends Cubit<GetSurveyAnsState> {
|
||||
final GetSurveyAnsRepository _getSurveyAnsRepository;
|
||||
|
||||
GetSurveyAnsCubit(this._getSurveyAnsRepository) : super(GetSurveyAnsInitial());
|
||||
|
||||
void getSurveyAns({required String langId}) async {
|
||||
try {
|
||||
emit(GetSurveyAnsFetchInProgress());
|
||||
final result = await _getSurveyAnsRepository.getSurveyAns(langId: langId);
|
||||
emit(GetSurveyAnsFetchSuccess(getSurveyAns: result['GetSurveyAns']));
|
||||
} catch (e) {
|
||||
emit(GetSurveyAnsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
35
news-app/lib/cubits/getUserDataByIdCubit.dart
Normal file
35
news-app/lib/cubits/getUserDataByIdCubit.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/GetUserById/getUserByIdRepository.dart';
|
||||
|
||||
abstract class GetUserByIdState {}
|
||||
|
||||
class GetUserByIdInitial extends GetUserByIdState {}
|
||||
|
||||
class GetUserByIdFetchInProgress extends GetUserByIdState {}
|
||||
|
||||
class GetUserByIdFetchSuccess extends GetUserByIdState {
|
||||
var result;
|
||||
|
||||
GetUserByIdFetchSuccess({required this.result});
|
||||
}
|
||||
|
||||
class GetUserByIdFetchFailure extends GetUserByIdState {
|
||||
final String errorMessage;
|
||||
|
||||
GetUserByIdFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class GetUserByIdCubit extends Cubit<GetUserByIdState> {
|
||||
final GetUserByIdRepository _getUserByIdRepository;
|
||||
|
||||
GetUserByIdCubit(this._getUserByIdRepository) : super(GetUserByIdInitial());
|
||||
|
||||
void getUserById() {
|
||||
emit(GetUserByIdFetchInProgress());
|
||||
_getUserByIdRepository.getUserById().then((value) {
|
||||
emit(GetUserByIdFetchSuccess(result: value));
|
||||
}).catchError((e) {
|
||||
emit(GetUserByIdFetchFailure(e.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
76
news-app/lib/cubits/getUserDraftedNewsCubit.dart
Normal file
76
news-app/lib/cubits/getUserDraftedNewsCubit.dart
Normal file
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class GetUserDraftedNewsState {}
|
||||
|
||||
class GetUserDraftedNewsInitial extends GetUserDraftedNewsState {}
|
||||
|
||||
class GetUserDraftedNewsFetchInProgress extends GetUserDraftedNewsState {}
|
||||
|
||||
class GetUserDraftedNewsFetchSuccess extends GetUserDraftedNewsState {
|
||||
final List<NewsModel> GetUserDraftedNews;
|
||||
final int totalGetUserDraftedNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
GetUserDraftedNewsFetchSuccess({required this.GetUserDraftedNews, required this.totalGetUserDraftedNewsCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class GetUserDraftedNewsFetchFailure extends GetUserDraftedNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
GetUserDraftedNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class GetUserDraftedNewsCubit extends Cubit<GetUserDraftedNewsState> {
|
||||
GetUserDraftedNewsCubit() : super(GetUserDraftedNewsInitial());
|
||||
|
||||
void getGetUserDraftedNews({int? userId}) async {
|
||||
try {
|
||||
emit(GetUserDraftedNewsFetchInProgress());
|
||||
final apiUrl = "${Api.getDraftNewsApi}/${userId}";
|
||||
final result = await Api.sendApiRequest(body: null, url: apiUrl);
|
||||
(!result[ERROR])
|
||||
? emit(GetUserDraftedNewsFetchSuccess(
|
||||
GetUserDraftedNews: (result[DATA][NEWS][DATA] as List).map((e) => NewsModel.fromJson(e)).toList(),
|
||||
totalGetUserDraftedNewsCount: result[DATA][NEWS][TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: (result[DATA][NEWS][DATA] as List).length < result[DATA][NEWS][TOTAL]))
|
||||
: emit(GetUserDraftedNewsFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(GetUserDraftedNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreGetUserDraftedNews() {
|
||||
return (state is GetUserDraftedNewsFetchSuccess) ? (state as GetUserDraftedNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void deleteNews(int index) {
|
||||
if (state is GetUserDraftedNewsFetchSuccess) {
|
||||
List<NewsModel> newsList = List.from((state as GetUserDraftedNewsFetchSuccess).GetUserDraftedNews)..removeAt(index);
|
||||
|
||||
emit(GetUserDraftedNewsFetchSuccess(
|
||||
GetUserDraftedNews: newsList,
|
||||
hasMore: (state as GetUserDraftedNewsFetchSuccess).hasMore,
|
||||
hasMoreFetchError: false,
|
||||
totalGetUserDraftedNewsCount: (state as GetUserDraftedNewsFetchSuccess).totalGetUserDraftedNewsCount - 1));
|
||||
}
|
||||
}
|
||||
|
||||
void deleteImageId(int index) {
|
||||
if (state is GetUserDraftedNewsFetchSuccess) {
|
||||
List<NewsModel> newsList = (state as GetUserDraftedNewsFetchSuccess).GetUserDraftedNews;
|
||||
|
||||
newsList[index].imageDataList!.removeAt(index);
|
||||
|
||||
emit(GetUserDraftedNewsFetchSuccess(
|
||||
GetUserDraftedNews: newsList,
|
||||
hasMore: (state as GetUserDraftedNewsFetchSuccess).hasMore,
|
||||
hasMoreFetchError: false,
|
||||
totalGetUserDraftedNewsCount: (state as GetUserDraftedNewsFetchSuccess).totalGetUserDraftedNewsCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
87
news-app/lib/cubits/getUserNewsCubit.dart
Normal file
87
news-app/lib/cubits/getUserNewsCubit.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/GetUserNews/getUserNewsRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class GetUserNewsState {}
|
||||
|
||||
class GetUserNewsInitial extends GetUserNewsState {}
|
||||
|
||||
class GetUserNewsFetchInProgress extends GetUserNewsState {}
|
||||
|
||||
class GetUserNewsFetchSuccess extends GetUserNewsState {
|
||||
final List<NewsModel> getUserNews;
|
||||
final int totalGetUserNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
GetUserNewsFetchSuccess({required this.getUserNews, required this.totalGetUserNewsCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class GetUserNewsFetchFailure extends GetUserNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
GetUserNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class GetUserNewsCubit extends Cubit<GetUserNewsState> {
|
||||
final GetUserNewsRepository _getUserNewsRepository;
|
||||
|
||||
GetUserNewsCubit(this._getUserNewsRepository) : super(GetUserNewsInitial());
|
||||
|
||||
void getGetUserNews({String? latitude, String? longitude}) async {
|
||||
try {
|
||||
emit(GetUserNewsFetchInProgress());
|
||||
final result = await _getUserNewsRepository.getGetUserNews(limit: limitOfAPIData.toString(), offset: "0", latitude: latitude, longitude: longitude);
|
||||
(!result[ERROR])
|
||||
? emit(GetUserNewsFetchSuccess(
|
||||
getUserNews: result['GetUserNews'], totalGetUserNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: (result['GetUserNews'] as List<NewsModel>).length < result[TOTAL]))
|
||||
: emit(GetUserNewsFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(GetUserNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreGetUserNews() {
|
||||
return (state is GetUserNewsFetchSuccess) ? (state as GetUserNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreGetUserNews({String? latitude, String? longitude}) async {
|
||||
if (state is GetUserNewsFetchSuccess) {
|
||||
try {
|
||||
final result = await _getUserNewsRepository.getGetUserNews(
|
||||
limit: limitOfAPIData.toString(), offset: (state as GetUserNewsFetchSuccess).getUserNews.length.toString(), latitude: latitude, longitude: longitude);
|
||||
List<NewsModel> updatedResults = (state as GetUserNewsFetchSuccess).getUserNews;
|
||||
updatedResults.addAll(result['GetUserNews'] as List<NewsModel>);
|
||||
emit(GetUserNewsFetchSuccess(getUserNews: updatedResults, totalGetUserNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(GetUserNewsFetchSuccess(
|
||||
getUserNews: (state as GetUserNewsFetchSuccess).getUserNews,
|
||||
hasMoreFetchError: true,
|
||||
totalGetUserNewsCount: (state as GetUserNewsFetchSuccess).totalGetUserNewsCount,
|
||||
hasMore: (state as GetUserNewsFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void deleteNews(int index) {
|
||||
if (state is GetUserNewsFetchSuccess) {
|
||||
List<NewsModel> newsList = List.from((state as GetUserNewsFetchSuccess).getUserNews)..removeAt(index);
|
||||
|
||||
emit(GetUserNewsFetchSuccess(
|
||||
getUserNews: newsList, hasMore: (state as GetUserNewsFetchSuccess).hasMore, hasMoreFetchError: false, totalGetUserNewsCount: (state as GetUserNewsFetchSuccess).totalGetUserNewsCount - 1));
|
||||
}
|
||||
}
|
||||
|
||||
void deleteImageId(int index) {
|
||||
if (state is GetUserNewsFetchSuccess) {
|
||||
List<NewsModel> newsList = (state as GetUserNewsFetchSuccess).getUserNews;
|
||||
|
||||
newsList[index].imageDataList!.removeAt(index);
|
||||
|
||||
emit(GetUserNewsFetchSuccess(
|
||||
getUserNews: newsList, hasMore: (state as GetUserNewsFetchSuccess).hasMore, hasMoreFetchError: false, totalGetUserNewsCount: (state as GetUserNewsFetchSuccess).totalGetUserNewsCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
47
news-app/lib/cubits/languageCubit.dart
Normal file
47
news-app/lib/cubits/languageCubit.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/appLanguageModel.dart';
|
||||
import 'package:news/data/repositories/language/languageRepository.dart';
|
||||
|
||||
abstract class LanguageState {}
|
||||
|
||||
class LanguageInitial extends LanguageState {}
|
||||
|
||||
class LanguageFetchInProgress extends LanguageState {}
|
||||
|
||||
class LanguageFetchSuccess extends LanguageState {
|
||||
final List<LanguageModel> language;
|
||||
|
||||
LanguageFetchSuccess({required this.language});
|
||||
}
|
||||
|
||||
class LanguageFetchFailure extends LanguageState {
|
||||
final String errorMessage;
|
||||
|
||||
LanguageFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LanguageCubit extends Cubit<LanguageState> {
|
||||
final LanguageRepository _languageRepository;
|
||||
|
||||
LanguageCubit(this._languageRepository) : super(LanguageInitial());
|
||||
|
||||
Future<List<LanguageModel>> getLanguage() async {
|
||||
try {
|
||||
emit(LanguageFetchInProgress());
|
||||
final result = await _languageRepository.getLanguage();
|
||||
emit(LanguageFetchSuccess(language: result['Language']));
|
||||
return result['Language'];
|
||||
} catch (e) {
|
||||
emit(LanguageFetchFailure(e.toString()));
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
List<LanguageModel> langList() {
|
||||
return (state is LanguageFetchSuccess) ? (state as LanguageFetchSuccess).language : [];
|
||||
}
|
||||
|
||||
int getLanguageIndex({required String langName}) {
|
||||
return (state is LanguageFetchSuccess) ? (state as LanguageFetchSuccess).language.indexWhere((element) => element.language == langName) : 0;
|
||||
}
|
||||
}
|
||||
57
news-app/lib/cubits/languageJsonCubit.dart
Normal file
57
news-app/lib/cubits/languageJsonCubit.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/LanguageJson/languageJsonRepository.dart';
|
||||
import 'package:news/utils/appLanguages.dart';
|
||||
|
||||
abstract class LanguageJsonState {}
|
||||
|
||||
class LanguageJsonInitial extends LanguageJsonState {}
|
||||
|
||||
class LanguageJsonFetchInProgress extends LanguageJsonState {}
|
||||
|
||||
class LanguageJsonFetchSuccess extends LanguageJsonState {
|
||||
Map<dynamic, dynamic> languageJson;
|
||||
|
||||
LanguageJsonFetchSuccess({required this.languageJson});
|
||||
}
|
||||
|
||||
class LanguageJsonFetchFailure extends LanguageJsonState {
|
||||
final String errorMessage;
|
||||
|
||||
LanguageJsonFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LanguageJsonCubit extends Cubit<LanguageJsonState> {
|
||||
final LanguageJsonRepository _languageJsonRepository;
|
||||
|
||||
LanguageJsonCubit(this._languageJsonRepository) : super(LanguageJsonInitial());
|
||||
|
||||
void fetchCurrentLanguageAndLabels(String currentLanguage) async {
|
||||
try {
|
||||
emit(LanguageJsonFetchInProgress());
|
||||
|
||||
await _languageJsonRepository.fetchLanguageLabels(currentLanguage).then((value) {
|
||||
emit(LanguageJsonFetchSuccess(languageJson: value));
|
||||
});
|
||||
} catch (e) {
|
||||
emit(LanguageJsonFetchSuccess(languageJson: appLanguageLabelKeys));
|
||||
}
|
||||
}
|
||||
|
||||
void getLanguageJson({required String lanCode}) async {
|
||||
try {
|
||||
emit(LanguageJsonFetchInProgress());
|
||||
final result = await _languageJsonRepository.getLanguageJson(lanCode: lanCode);
|
||||
emit(LanguageJsonFetchSuccess(languageJson: result));
|
||||
} catch (e) {
|
||||
emit(LanguageJsonFetchSuccess(languageJson: appLanguageLabelKeys));
|
||||
}
|
||||
}
|
||||
|
||||
String getTranslatedLabels(String label) {
|
||||
if (state is LanguageJsonFetchSuccess) {
|
||||
return (state as LanguageJsonFetchSuccess).languageJson[label] ?? appLanguageLabelKeys[label] ?? label;
|
||||
} else {
|
||||
return appLanguageLabelKeys[label] ?? label;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
news-app/lib/cubits/liveStreamCubit.dart
Normal file
39
news-app/lib/cubits/liveStreamCubit.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/LiveStreamingModel.dart';
|
||||
import 'package:news/data/repositories/LiveStream/liveStreamRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class LiveStreamState {}
|
||||
|
||||
class LiveStreamInitial extends LiveStreamState {}
|
||||
|
||||
class LiveStreamFetchInProgress extends LiveStreamState {}
|
||||
|
||||
class LiveStreamFetchSuccess extends LiveStreamState {
|
||||
final List<LiveStreamingModel> liveStream;
|
||||
|
||||
LiveStreamFetchSuccess({required this.liveStream});
|
||||
}
|
||||
|
||||
class LiveStreamFetchFailure extends LiveStreamState {
|
||||
final String errorMessage;
|
||||
|
||||
LiveStreamFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LiveStreamCubit extends Cubit<LiveStreamState> {
|
||||
final LiveStreamRepository _liveStreamRepository;
|
||||
|
||||
LiveStreamCubit(this._liveStreamRepository) : super(LiveStreamInitial());
|
||||
|
||||
void getLiveStream({required String langId}) async {
|
||||
try {
|
||||
emit(LiveStreamFetchInProgress());
|
||||
final result = await _liveStreamRepository.getLiveStream(langId: langId);
|
||||
|
||||
(!result[ERROR]) ? emit(LiveStreamFetchSuccess(liveStream: result['LiveStream'])) : emit(LiveStreamFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(LiveStreamFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
73
news-app/lib/cubits/locationCityCubit.dart
Normal file
73
news-app/lib/cubits/locationCityCubit.dart
Normal file
@@ -0,0 +1,73 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/locationCityModel.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class LocationCityState {}
|
||||
|
||||
class LocationCityInitial extends LocationCityState {}
|
||||
|
||||
class LocationCityFetchInProgress extends LocationCityState {}
|
||||
|
||||
class LocationCityFetchSuccess extends LocationCityState {
|
||||
final List<LocationCityModel> locationCity;
|
||||
final int totalLocations;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
LocationCityFetchSuccess({required this.locationCity, required this.totalLocations, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class LocationCityFetchFailure extends LocationCityState {
|
||||
final String errorMessage;
|
||||
|
||||
LocationCityFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class LocationCityCubit extends Cubit<LocationCityState> {
|
||||
LocationCityCubit() : super(LocationCityInitial());
|
||||
|
||||
void getLocationCity() async {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(body: {LIMIT: limitOfAPIData, OFFSET: 0}, url: Api.getLocationCityApi);
|
||||
emit(LocationCityFetchSuccess(
|
||||
totalLocations: result[TOTAL],
|
||||
locationCity: (result[DATA] as List).map((e) => LocationCityModel.fromJson(e)).toList(),
|
||||
hasMore: (result[DATA] as List).map((e) => LocationCityModel.fromJson(e)).toList().length < result[TOTAL],
|
||||
hasMoreFetchError: false));
|
||||
} catch (e) {
|
||||
emit(LocationCityFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
void getMoreLocationCity() async {
|
||||
if (state is LocationCityFetchSuccess) {
|
||||
try {
|
||||
await Api.sendApiRequest(body: {LIMIT: limitOfAPIData, OFFSET: (state as LocationCityFetchSuccess).locationCity.length.toString()}, url: Api.getLocationCityApi).then((value) {
|
||||
List<LocationCityModel> updatedResults = (state as LocationCityFetchSuccess).locationCity;
|
||||
updatedResults.addAll((value[DATA] as List).map((e) => LocationCityModel.fromJson(e)).toList());
|
||||
emit(LocationCityFetchSuccess(locationCity: updatedResults, totalLocations: value[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < value[TOTAL]));
|
||||
});
|
||||
} catch (e) {
|
||||
emit(LocationCityFetchSuccess(
|
||||
locationCity: (state as LocationCityFetchSuccess).locationCity,
|
||||
totalLocations: (state as LocationCityFetchSuccess).totalLocations,
|
||||
hasMoreFetchError: true,
|
||||
hasMore: (state as LocationCityFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreLocation() {
|
||||
return (state is LocationCityFetchSuccess) ? (state as LocationCityFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
List<LocationCityModel> getLocationCityList() {
|
||||
return (state is LocationCityFetchSuccess) ? (state as LocationCityFetchSuccess).locationCity : [];
|
||||
}
|
||||
|
||||
int getLocationIndex({required String locationName}) {
|
||||
return (state is LocationCityFetchSuccess) ? (state as LocationCityFetchSuccess).locationCity.indexWhere((element) => element.locationName == locationName) : 0;
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/otherPagesCubit.dart
Normal file
37
news-app/lib/cubits/otherPagesCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/OtherPageModel.dart';
|
||||
import 'package:news/data/repositories/OtherPages/otherPagesRepository.dart';
|
||||
|
||||
abstract class OtherPageState {}
|
||||
|
||||
class OtherPageInitial extends OtherPageState {}
|
||||
|
||||
class OtherPageFetchInProgress extends OtherPageState {}
|
||||
|
||||
class OtherPageFetchSuccess extends OtherPageState {
|
||||
final List<OtherPageModel> otherPage;
|
||||
|
||||
OtherPageFetchSuccess({required this.otherPage});
|
||||
}
|
||||
|
||||
class OtherPageFetchFailure extends OtherPageState {
|
||||
final String errorMessage;
|
||||
|
||||
OtherPageFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class OtherPageCubit extends Cubit<OtherPageState> {
|
||||
final OtherPageRepository _otherPageRepository;
|
||||
|
||||
OtherPageCubit(this._otherPageRepository) : super(OtherPageInitial());
|
||||
|
||||
void getOtherPage({required String langId}) async {
|
||||
emit(OtherPageFetchInProgress());
|
||||
try {
|
||||
final result = await _otherPageRepository.getOtherPage(langId: langId);
|
||||
emit(OtherPageFetchSuccess(otherPage: result['OtherPage']));
|
||||
} catch (e) {
|
||||
emit(OtherPageFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
38
news-app/lib/cubits/privacyTermsCubit.dart
Normal file
38
news-app/lib/cubits/privacyTermsCubit.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/OtherPageModel.dart';
|
||||
import 'package:news/data/repositories/OtherPages/otherPagesRepository.dart';
|
||||
|
||||
abstract class PrivacyTermsState {}
|
||||
|
||||
class PrivacyTermsInitial extends PrivacyTermsState {}
|
||||
|
||||
class PrivacyTermsFetchInProgress extends PrivacyTermsState {}
|
||||
|
||||
class PrivacyTermsFetchSuccess extends PrivacyTermsState {
|
||||
final OtherPageModel termsPolicy;
|
||||
final OtherPageModel privacyPolicy;
|
||||
|
||||
PrivacyTermsFetchSuccess({required this.termsPolicy, required this.privacyPolicy});
|
||||
}
|
||||
|
||||
class PrivacyTermsFetchFailure extends PrivacyTermsState {
|
||||
final String errorMessage;
|
||||
|
||||
PrivacyTermsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class PrivacyTermsCubit extends Cubit<PrivacyTermsState> {
|
||||
final OtherPageRepository _otherPageRepository;
|
||||
|
||||
PrivacyTermsCubit(this._otherPageRepository) : super(PrivacyTermsInitial());
|
||||
|
||||
void getPrivacyTerms({required String langId}) async {
|
||||
emit(PrivacyTermsFetchInProgress());
|
||||
try {
|
||||
final Map<String, dynamic> result = await _otherPageRepository.getPrivacyTermsPage(langId: langId);
|
||||
emit(PrivacyTermsFetchSuccess(privacyPolicy: OtherPageModel.fromPrivacyTermsJson(result['privacy_policy']), termsPolicy: OtherPageModel.fromPrivacyTermsJson(result['terms_policy'])));
|
||||
} catch (e) {
|
||||
emit(PrivacyTermsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
77
news-app/lib/cubits/relatedNewsCubit.dart
Normal file
77
news-app/lib/cubits/relatedNewsCubit.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/RelatedNews/relatedNewsRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class RelatedNewsState {}
|
||||
|
||||
class RelatedNewsInitial extends RelatedNewsState {}
|
||||
|
||||
class RelatedNewsFetchInProgress extends RelatedNewsState {}
|
||||
|
||||
class RelatedNewsFetchSuccess extends RelatedNewsState {
|
||||
final List<NewsModel> relatedNews;
|
||||
final int totalRelatedNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
RelatedNewsFetchSuccess({required this.relatedNews, required this.totalRelatedNewsCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class RelatedNewsFetchFailure extends RelatedNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
RelatedNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class RelatedNewsCubit extends Cubit<RelatedNewsState> {
|
||||
final RelatedNewsRepository _relatedNewsRepository;
|
||||
|
||||
RelatedNewsCubit(this._relatedNewsRepository) : super(RelatedNewsInitial());
|
||||
|
||||
void getRelatedNews({required String langId, String? catId, String? subCatId}) async {
|
||||
try {
|
||||
emit(RelatedNewsFetchInProgress());
|
||||
final result = await _relatedNewsRepository.getRelatedNews(perPage: limitOfAPIData.toString(), offset: "0", langId: langId, catId: catId, subCatId: subCatId);
|
||||
emit(RelatedNewsFetchSuccess(
|
||||
relatedNews: result['RelatedNews'], totalRelatedNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: (result['RelatedNews'] as List<NewsModel>).length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(RelatedNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreRelatedNews() {
|
||||
return (state is RelatedNewsFetchSuccess) ? (state as RelatedNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreRelatedNews({required String langId, String? catId, String? subCatId, String? latitude, String? longitude}) async {
|
||||
if (state is RelatedNewsFetchSuccess) {
|
||||
try {
|
||||
final result = await _relatedNewsRepository.getRelatedNews(
|
||||
perPage: limitOfAPIData.toString(),
|
||||
offset: (state as RelatedNewsFetchSuccess).relatedNews.length.toString(),
|
||||
langId: langId,
|
||||
subCatId: subCatId,
|
||||
catId: catId,
|
||||
latitude: latitude,
|
||||
longitude: longitude);
|
||||
List<NewsModel> updatedResults = (state as RelatedNewsFetchSuccess).relatedNews;
|
||||
updatedResults.addAll(result['RelatedNews'] as List<NewsModel>);
|
||||
emit(RelatedNewsFetchSuccess(
|
||||
relatedNews: updatedResults,
|
||||
totalRelatedNewsCount: result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: updatedResults.length < result[TOTAL],
|
||||
));
|
||||
} catch (e) {
|
||||
emit(RelatedNewsFetchSuccess(
|
||||
relatedNews: (state as RelatedNewsFetchSuccess).relatedNews,
|
||||
hasMoreFetchError: true,
|
||||
totalRelatedNewsCount: (state as RelatedNewsFetchSuccess).totalRelatedNewsCount,
|
||||
hasMore: (state as RelatedNewsFetchSuccess).hasMore,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
71
news-app/lib/cubits/rssFeedCubit.dart
Normal file
71
news-app/lib/cubits/rssFeedCubit.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/RSSFeedModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class RSSFeedState {}
|
||||
|
||||
class RSSFeedInitial extends RSSFeedState {}
|
||||
|
||||
class RSSFeedFetchInProgress extends RSSFeedState {}
|
||||
|
||||
class RSSFeedFetchSuccess extends RSSFeedState {
|
||||
final List<RSSFeedModel> RSSFeed;
|
||||
final int totalRSSFeedCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
RSSFeedFetchSuccess({required this.RSSFeed, required this.totalRSSFeedCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class RSSFeedFetchFailure extends RSSFeedState {
|
||||
final String errorMessage;
|
||||
|
||||
RSSFeedFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class RSSFeedCubit extends Cubit<RSSFeedState> {
|
||||
RSSFeedCubit() : super(RSSFeedInitial());
|
||||
int limit = 10;
|
||||
|
||||
void getRSSFeed({required String langId, String? categoryId, String? subCategoryId}) async {
|
||||
try {
|
||||
emit(RSSFeedFetchInProgress());
|
||||
|
||||
final result = await Api.sendApiRequest(
|
||||
body: {LANGUAGE_ID: langId, if (categoryId != null) CATEGORY_ID: categoryId, if (subCategoryId != null) SUBCAT_ID: subCategoryId, LIMIT: limit, OFFSET: 0}, url: Api.rssFeedApi);
|
||||
|
||||
(!result[ERROR])
|
||||
? emit(RSSFeedFetchSuccess(
|
||||
RSSFeed: (result[DATA] as List).map((e) => RSSFeedModel.fromJson(e)).toList(), totalRSSFeedCount: result[TOTAL], hasMoreFetchError: false, hasMore: result.length < result[TOTAL]))
|
||||
: emit(RSSFeedFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(RSSFeedFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreRSSFeed() {
|
||||
return (state is RSSFeedFetchSuccess) ? (state as RSSFeedFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreRSSFeed({required String langId}) async {
|
||||
if (state is RSSFeedFetchSuccess) {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(body: {LANGUAGE_ID: langId, LIMIT: limit, OFFSET: (state as RSSFeedFetchSuccess).RSSFeed.length}, url: Api.rssFeedApi);
|
||||
if (!result[ERROR]) {
|
||||
List<RSSFeedModel> updatedResults = (state as RSSFeedFetchSuccess).RSSFeed;
|
||||
updatedResults.addAll((result[DATA] as List).map((e) => RSSFeedModel.fromJson(e)).toList());
|
||||
emit(RSSFeedFetchSuccess(RSSFeed: updatedResults, totalRSSFeedCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} else {
|
||||
emit(RSSFeedFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(RSSFeedFetchSuccess(
|
||||
RSSFeed: (state as RSSFeedFetchSuccess).RSSFeed,
|
||||
hasMoreFetchError: true,
|
||||
totalRSSFeedCount: (state as RSSFeedFetchSuccess).totalRSSFeedCount,
|
||||
hasMore: (state as RSSFeedFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
132
news-app/lib/cubits/sectionByIdCubit.dart
Normal file
132
news-app/lib/cubits/sectionByIdCubit.dart
Normal file
@@ -0,0 +1,132 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/BreakingNewsModel.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/SectionById/sectionByIdRepository.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SectionByIdState {}
|
||||
|
||||
class SectionByIdInitial extends SectionByIdState {}
|
||||
|
||||
class SectionByIdFetchInProgress extends SectionByIdState {}
|
||||
|
||||
class SectionByIdFetchSuccess extends SectionByIdState {
|
||||
final List<NewsModel> newsModel;
|
||||
final List<BreakingNewsModel> breakNewsModel;
|
||||
final int totalCount;
|
||||
final String type;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
SectionByIdFetchSuccess({required this.newsModel, required this.breakNewsModel, required this.totalCount, required this.type, required this.hasMore, required this.hasMoreFetchError});
|
||||
}
|
||||
|
||||
class SectionByIdFetchFailure extends SectionByIdState {
|
||||
final String errorMessage;
|
||||
|
||||
SectionByIdFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SectionByIdCubit extends Cubit<SectionByIdState> {
|
||||
final SectionByIdRepository _sectionByIdRepository;
|
||||
final int limitOfFeaturedSectionData = 10;
|
||||
|
||||
SectionByIdCubit(this._sectionByIdRepository) : super(SectionByIdInitial());
|
||||
|
||||
void getSectionById({required String langId, required String sectionId, String? latitude, String? longitude, String? limit, String? offset}) async {
|
||||
try {
|
||||
emit(SectionByIdFetchInProgress());
|
||||
final result = await _sectionByIdRepository.getSectionById(
|
||||
offset: offset ?? "0", limit: limit ?? limitOfFeaturedSectionData.toString(), langId: langId, sectionId: sectionId, latitude: latitude, longitude: longitude);
|
||||
if (!result[ERROR]) {
|
||||
int totalSections = (result[DATA][0].newsType == "news" || result[DATA][0].newsType == "user_choice")
|
||||
? result[DATA][0].newsTotal!
|
||||
: result[DATA][0].newsType == "breaking_news"
|
||||
? result[DATA][0].breakNewsTotal!
|
||||
: result[DATA][0].videosTotal!;
|
||||
List<NewsModel> newsSection = (result[DATA][0].newsType == "news" || result[DATA][0].newsType == "user_choice")
|
||||
? result[DATA][0].news!
|
||||
: result[DATA][0].videosType == "news"
|
||||
? result[DATA][0].videos!
|
||||
: [];
|
||||
List<BreakingNewsModel> brNewsSection = result[DATA][0].newsType == "breaking_news"
|
||||
? result[DATA][0].breakNews!
|
||||
: result[DATA][0].videosType == "breaking_news"
|
||||
? result[DATA][0].breakVideos!
|
||||
: [];
|
||||
|
||||
emit(SectionByIdFetchSuccess(
|
||||
newsModel: newsSection,
|
||||
breakNewsModel: brNewsSection,
|
||||
totalCount: totalSections,
|
||||
type: result[DATA][0].newsType!,
|
||||
hasMore: ((result[DATA][0].newsType! == NEWS) ? (newsSection.length < totalSections) : (brNewsSection.length < totalSections)),
|
||||
hasMoreFetchError: false));
|
||||
} else {
|
||||
emit(SectionByIdFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
if (!isClosed) emit(SectionByIdFetchFailure(e.toString())); //isClosed checked to resolve Bad state issue of Bloc
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreSections() {
|
||||
return (state is SectionByIdFetchSuccess) ? (state as SectionByIdFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreSectionById({required String langId, required String sectionId, String? latitude, String? longitude, String? limit, String? offset}) async {
|
||||
if (state is SectionByIdFetchSuccess) {
|
||||
try {
|
||||
final result = await _sectionByIdRepository.getSectionById(
|
||||
sectionId: sectionId,
|
||||
latitude: latitude,
|
||||
longitude: longitude,
|
||||
limit: limit ?? limitOfFeaturedSectionData.toString(),
|
||||
offset: (state as SectionByIdFetchSuccess).newsModel.length.toString(),
|
||||
langId: langId);
|
||||
List<NewsModel> updatedResults = [];
|
||||
List<BreakingNewsModel> updatedBrResults = [];
|
||||
|
||||
if (result[DATA][0].newsType! == NEWS || result[DATA][0].videosType == NEWS) {
|
||||
updatedResults = (state as SectionByIdFetchSuccess).newsModel;
|
||||
List<NewsModel> newValues = (result[DATA][0].newsType == "news" || result[DATA][0].newsType == "user_choice")
|
||||
? result[DATA][0].news ?? []
|
||||
: result[DATA][0].videosType == "news"
|
||||
? result[DATA][0].videos ?? []
|
||||
: [];
|
||||
updatedResults.addAll(newValues);
|
||||
} else {
|
||||
updatedBrResults = (state as SectionByIdFetchSuccess).breakNewsModel;
|
||||
List<BreakingNewsModel> newValues = result[DATA][0].newsType == "breaking_news"
|
||||
? result[DATA][0].breakNews!
|
||||
: result[DATA][0].videosType == "breaking_news"
|
||||
? result[DATA][0].breakVideos!
|
||||
: [];
|
||||
updatedBrResults.addAll(newValues);
|
||||
}
|
||||
|
||||
int totalCount = (result[DATA][0].newsType == "news" || result[DATA][0].newsType == "user_choice")
|
||||
? result[DATA][0].newsTotal!
|
||||
: result[DATA][0].newsType == "breaking_news"
|
||||
? result[DATA][0].breakNewsTotal!
|
||||
: result[DATA][0].videosTotal!;
|
||||
|
||||
emit(SectionByIdFetchSuccess(
|
||||
newsModel: updatedResults,
|
||||
breakNewsModel: updatedBrResults,
|
||||
type: result[DATA][0].newsType!,
|
||||
totalCount: totalCount,
|
||||
hasMoreFetchError: false,
|
||||
hasMore: (result[DATA][0].newsType! == NEWS || result[DATA][0].videosType == NEWS) ? (updatedResults.length < totalCount) : (updatedBrResults.length < totalCount)));
|
||||
} catch (e) {
|
||||
emit(SectionByIdFetchSuccess(
|
||||
type: (state as SectionByIdFetchSuccess).type,
|
||||
breakNewsModel: (state as SectionByIdFetchSuccess).breakNewsModel,
|
||||
newsModel: (state as SectionByIdFetchSuccess).newsModel,
|
||||
hasMoreFetchError: (e.toString() == "No Data Found") ? false : true,
|
||||
totalCount: (state as SectionByIdFetchSuccess).totalCount,
|
||||
hasMore: (state as SectionByIdFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/setNewsViewsCubit.dart
Normal file
37
news-app/lib/cubits/setNewsViewsCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/SetNewsViews/setNewsViewsRepository.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
abstract class SetNewsViewsState {}
|
||||
|
||||
class SetNewsViewsInitial extends SetNewsViewsState {}
|
||||
|
||||
class SetNewsViewsInProgress extends SetNewsViewsState {}
|
||||
|
||||
class SetNewsViewsSuccess extends SetNewsViewsState {
|
||||
final String message;
|
||||
|
||||
SetNewsViewsSuccess(this.message);
|
||||
}
|
||||
|
||||
class SetNewsViewsFailure extends SetNewsViewsState {
|
||||
final String errorMessage;
|
||||
|
||||
SetNewsViewsFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SetNewsViewsCubit extends Cubit<SetNewsViewsState> {
|
||||
final SetNewsViewsRepository setNewsViewsRepository;
|
||||
|
||||
SetNewsViewsCubit(this.setNewsViewsRepository) : super(SetNewsViewsInitial());
|
||||
|
||||
void setNewsViews({required String newsId, required bool isBreakingNews}) {
|
||||
emit(SetNewsViewsInProgress());
|
||||
setNewsViewsRepository.setNewsViews(newsId: newsId, isBreakingNews: isBreakingNews).then((value) {
|
||||
emit(SetNewsViewsSuccess(value["message"]));
|
||||
}).catchError((e) {
|
||||
ApiMessageAndCodeException apiMessageAndCodeException = e;
|
||||
emit(SetNewsViewsFailure(apiMessageAndCodeException.errorMessage.toString()));
|
||||
});
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/setSurveyAnswerCubit.dart
Normal file
37
news-app/lib/cubits/setSurveyAnswerCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/SetSurveyAnswer/setSurveyAnsRepository.dart';
|
||||
|
||||
abstract class SetSurveyAnsState {}
|
||||
|
||||
class SetSurveyAnsInitial extends SetSurveyAnsState {}
|
||||
|
||||
class SetSurveyAnsFetchInProgress extends SetSurveyAnsState {}
|
||||
|
||||
class SetSurveyAnsFetchSuccess extends SetSurveyAnsState {
|
||||
var setSurveyAns;
|
||||
|
||||
SetSurveyAnsFetchSuccess({required this.setSurveyAns});
|
||||
}
|
||||
|
||||
class SetSurveyAnsFetchFailure extends SetSurveyAnsState {
|
||||
final String errorMessage;
|
||||
|
||||
SetSurveyAnsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SetSurveyAnsCubit extends Cubit<SetSurveyAnsState> {
|
||||
final SetSurveyAnsRepository _setSurveyAnsRepository;
|
||||
|
||||
SetSurveyAnsCubit(this._setSurveyAnsRepository) : super(SetSurveyAnsInitial());
|
||||
|
||||
void setSurveyAns({required String queId, required String optId}) async {
|
||||
try {
|
||||
emit(SetSurveyAnsFetchInProgress());
|
||||
final result = await _setSurveyAnsRepository.setSurveyAns(queId: queId, optId: optId);
|
||||
|
||||
emit(SetSurveyAnsFetchSuccess(setSurveyAns: result['SetSurveyAns']));
|
||||
} catch (e) {
|
||||
emit(SetSurveyAnsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
41
news-app/lib/cubits/settingCubit.dart
Normal file
41
news-app/lib/cubits/settingCubit.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/SettingsModel.dart';
|
||||
import 'package:news/data/repositories/Settings/settingRepository.dart';
|
||||
|
||||
class SettingsState {
|
||||
final SettingsModel? settingsModel;
|
||||
|
||||
SettingsState({this.settingsModel});
|
||||
}
|
||||
|
||||
class SettingsCubit extends Cubit<SettingsState> {
|
||||
final SettingsRepository _settingsRepository;
|
||||
|
||||
SettingsCubit(this._settingsRepository) : super(SettingsState()) {
|
||||
_getCurrentSettings();
|
||||
}
|
||||
|
||||
void _getCurrentSettings() {
|
||||
emit(SettingsState(settingsModel: SettingsModel.fromJson(_settingsRepository.getCurrentSettings())));
|
||||
}
|
||||
|
||||
SettingsModel getSettings() {
|
||||
return state.settingsModel!;
|
||||
}
|
||||
|
||||
void changeShowIntroSlider(bool value) {
|
||||
_settingsRepository.changeIntroSlider(value);
|
||||
emit(SettingsState(settingsModel: state.settingsModel!.copyWith(showIntroSlider: value)));
|
||||
}
|
||||
|
||||
void changeFcmToken(String value) {
|
||||
_settingsRepository.changeFcmToken(value);
|
||||
emit(SettingsState(settingsModel: state.settingsModel!.copyWith(token: value)));
|
||||
}
|
||||
|
||||
void changeNotification(bool value) {
|
||||
//set HiveBoxKey value for Enabled Notifications
|
||||
_settingsRepository.changeNotification(value);
|
||||
emit(SettingsState(settingsModel: state.settingsModel!.copyWith(notification: value)));
|
||||
}
|
||||
}
|
||||
38
news-app/lib/cubits/slugCheckCubit.dart
Normal file
38
news-app/lib/cubits/slugCheckCubit.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SlugCheckState {}
|
||||
|
||||
class SlugCheckInitial extends SlugCheckState {}
|
||||
|
||||
class SlugCheckFetchInProgress extends SlugCheckState {}
|
||||
|
||||
class SlugCheckFetchSuccess extends SlugCheckState {
|
||||
String message;
|
||||
SlugCheckFetchSuccess({required this.message});
|
||||
}
|
||||
|
||||
class SlugCheckFetchFailure extends SlugCheckState {
|
||||
final String errorMessage;
|
||||
|
||||
SlugCheckFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SlugCheckCubit extends Cubit<SlugCheckState> {
|
||||
SlugCheckCubit() : super(SlugCheckInitial());
|
||||
|
||||
Future<void> checkSlugAvailability({required String slug, required String langId}) async {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(body: {SLUG: slug, LANGUAGE_ID: langId, LIMIT: limitOfAPIData, OFFSET: 0}, url: Api.slugCheckApi);
|
||||
if (result[ERROR] == true) {
|
||||
emit(SlugCheckFetchFailure(result[MESSAGE].toString()));
|
||||
} else {
|
||||
emit(SlugCheckFetchSuccess(message: result[MESSAGE]));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(SlugCheckFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
49
news-app/lib/cubits/slugNewsCubit.dart
Normal file
49
news-app/lib/cubits/slugNewsCubit.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SlugNewsState {}
|
||||
|
||||
class SlugNewsInitial extends SlugNewsState {}
|
||||
|
||||
class SlugNewsFetchInProgress extends SlugNewsState {}
|
||||
|
||||
class SlugNewsFetchSuccess extends SlugNewsState {
|
||||
final List<NewsModel> generalNews;
|
||||
final int totalCount;
|
||||
|
||||
SlugNewsFetchSuccess({required this.totalCount, required this.generalNews});
|
||||
}
|
||||
|
||||
class SlugNewsFetchFailure extends SlugNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
SlugNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SlugNewsCubit extends Cubit<SlugNewsState> {
|
||||
SlugNewsCubit() : super(SlugNewsInitial());
|
||||
|
||||
Future<dynamic> getSlugNews({required String langId, String? latitude, String? longitude, int? offset, String? newsSlug}) async {
|
||||
emit(SlugNewsInitial());
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId, LIMIT: 20};
|
||||
|
||||
if (latitude != null && latitude != "null") body[LATITUDE] = latitude;
|
||||
if (longitude != null && longitude != "null") body[LONGITUDE] = longitude;
|
||||
if (offset != null) body[OFFSET] = offset;
|
||||
if (newsSlug != null && newsSlug != "null" && newsSlug.trim().isNotEmpty) body[SLUG] = newsSlug; // used in case of native link , details screen redirection
|
||||
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getNewsApi);
|
||||
if (!result[ERROR]) {
|
||||
emit(SlugNewsFetchSuccess(generalNews: (result[DATA] as List).map((e) => NewsModel.fromJson(e)).toList(), totalCount: result[TOTAL]));
|
||||
} else {
|
||||
emit(SlugNewsFetchFailure(result[MESSAGE]));
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
81
news-app/lib/cubits/subCatNewsCubit.dart
Normal file
81
news-app/lib/cubits/subCatNewsCubit.dart
Normal file
@@ -0,0 +1,81 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/SubCatNews/subCatRepository.dart';
|
||||
import 'package:news/utils/ErrorMessageKeys.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class SubCatNewsState {}
|
||||
|
||||
class SubCatNewsInitial extends SubCatNewsState {}
|
||||
|
||||
class SubCatNewsFetchInProgress extends SubCatNewsState {}
|
||||
|
||||
class SubCatNewsFetchSuccess extends SubCatNewsState {
|
||||
final List<NewsModel> subCatNews;
|
||||
final int totalSubCatNewsCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
final bool isFirst;
|
||||
|
||||
SubCatNewsFetchSuccess({required this.subCatNews, required this.totalSubCatNewsCount, required this.hasMoreFetchError, required this.hasMore, required this.isFirst});
|
||||
}
|
||||
|
||||
class SubCatNewsFetchFailure extends SubCatNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
SubCatNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SubCatNewsCubit extends Cubit<SubCatNewsState> {
|
||||
final SubCatNewsRepository _subCatNewsRepository;
|
||||
|
||||
SubCatNewsCubit(this._subCatNewsRepository) : super(SubCatNewsInitial());
|
||||
|
||||
void getSubCatNews({String? catId, String? subCatId, String? latitude, String? longitude, required String langId}) async {
|
||||
try {
|
||||
emit(SubCatNewsFetchInProgress());
|
||||
final result =
|
||||
await _subCatNewsRepository.getSubCatNews(limit: limitOfAPIData.toString(), offset: "0", subCatId: subCatId, langId: langId, catId: catId, latitude: latitude, longitude: longitude);
|
||||
(!result[ERROR])
|
||||
? emit(SubCatNewsFetchSuccess(
|
||||
subCatNews: result['SubCatNews'],
|
||||
totalSubCatNewsCount: result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: (result['SubCatNews'] as List<NewsModel>).length < result[TOTAL],
|
||||
isFirst: true))
|
||||
: emit(SubCatNewsFetchFailure(ErrorMessageKeys.noDataMessage));
|
||||
} catch (e) {
|
||||
if (!isClosed) emit(SubCatNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreSubCatNews() {
|
||||
return (state is SubCatNewsFetchSuccess) ? (state as SubCatNewsFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreSubCatNews({String? catId, String? subCatId, String? latitude, String? longitude, required String langId}) async {
|
||||
if (state is SubCatNewsFetchSuccess) {
|
||||
try {
|
||||
final result = await _subCatNewsRepository.getSubCatNews(
|
||||
limit: limitOfAPIData.toString(),
|
||||
offset: (state as SubCatNewsFetchSuccess).subCatNews.length.toString(),
|
||||
langId: langId,
|
||||
catId: catId,
|
||||
subCatId: subCatId,
|
||||
latitude: latitude,
|
||||
longitude: longitude);
|
||||
List<NewsModel> updatedResults = (state as SubCatNewsFetchSuccess).subCatNews;
|
||||
updatedResults.addAll(result['SubCatNews'] as List<NewsModel>);
|
||||
emit(SubCatNewsFetchSuccess(subCatNews: updatedResults, totalSubCatNewsCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL], isFirst: false));
|
||||
} catch (e) {
|
||||
emit(SubCatNewsFetchSuccess(
|
||||
subCatNews: (state as SubCatNewsFetchSuccess).subCatNews,
|
||||
hasMoreFetchError: true,
|
||||
totalSubCatNewsCount: (state as SubCatNewsFetchSuccess).totalSubCatNewsCount,
|
||||
hasMore: (state as SubCatNewsFetchSuccess).hasMore,
|
||||
isFirst: false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
40
news-app/lib/cubits/subCategoryCubit.dart
Normal file
40
news-app/lib/cubits/subCategoryCubit.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/data/repositories/SubCategory/subCatRepository.dart';
|
||||
|
||||
abstract class SubCategoryState {}
|
||||
|
||||
class SubCategoryInitial extends SubCategoryState {}
|
||||
|
||||
class SubCategoryFetchInProgress extends SubCategoryState {}
|
||||
|
||||
class SubCategoryFetchSuccess extends SubCategoryState {
|
||||
final List<SubCategoryModel> subCategory;
|
||||
|
||||
SubCategoryFetchSuccess({required this.subCategory});
|
||||
}
|
||||
|
||||
class SubCategoryFetchFailure extends SubCategoryState {
|
||||
final String errorMessage;
|
||||
|
||||
SubCategoryFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SubCategoryCubit extends Cubit<SubCategoryState> {
|
||||
final SubCategoryRepository _subCategoryRepository;
|
||||
|
||||
SubCategoryCubit(this._subCategoryRepository) : super(SubCategoryInitial());
|
||||
|
||||
void getSubCategory({required BuildContext context, required String catId, required String langId}) async {
|
||||
try {
|
||||
emit(SubCategoryFetchInProgress());
|
||||
final result = await _subCategoryRepository.getSubCategory(context: context, catId: catId, langId: langId);
|
||||
|
||||
emit(SubCategoryFetchSuccess(subCategory: result['SubCategory']));
|
||||
} catch (e) {
|
||||
emit(SubCategoryFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
53
news-app/lib/cubits/surveyQuestionCubit.dart
Normal file
53
news-app/lib/cubits/surveyQuestionCubit.dart
Normal file
@@ -0,0 +1,53 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/SurveyQuestion/surveyQueRepository.dart';
|
||||
|
||||
abstract class SurveyQuestionState {}
|
||||
|
||||
class SurveyQuestionInitial extends SurveyQuestionState {}
|
||||
|
||||
class SurveyQuestionFetchInProgress extends SurveyQuestionState {}
|
||||
|
||||
class SurveyQuestionFetchSuccess extends SurveyQuestionState {
|
||||
final List<NewsModel> surveyQuestion;
|
||||
|
||||
SurveyQuestionFetchSuccess({required this.surveyQuestion});
|
||||
}
|
||||
|
||||
class SurveyQuestionFetchFailure extends SurveyQuestionState {
|
||||
final String errorMessage;
|
||||
|
||||
SurveyQuestionFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class SurveyQuestionCubit extends Cubit<SurveyQuestionState> {
|
||||
final SurveyQuestionRepository _surveyQuestionRepository;
|
||||
|
||||
SurveyQuestionCubit(this._surveyQuestionRepository) : super(SurveyQuestionInitial());
|
||||
|
||||
Future<void> getSurveyQuestion({required String langId}) async {
|
||||
try {
|
||||
emit(SurveyQuestionFetchInProgress());
|
||||
await _surveyQuestionRepository.getSurveyQuestion(langId: langId).then((value) {
|
||||
emit(SurveyQuestionFetchSuccess(surveyQuestion: value['SurveyQuestion']));
|
||||
});
|
||||
} catch (e) {
|
||||
emit(SurveyQuestionFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
void removeQuestion(String index) {
|
||||
if (state is SurveyQuestionFetchSuccess) {
|
||||
List<NewsModel> queList = List.from((state as SurveyQuestionFetchSuccess).surveyQuestion)..removeWhere((element) => element.id! == index);
|
||||
emit(SurveyQuestionFetchSuccess(surveyQuestion: queList));
|
||||
}
|
||||
}
|
||||
|
||||
List surveyList() {
|
||||
return (state is SurveyQuestionFetchSuccess) ? (state as SurveyQuestionFetchSuccess).surveyQuestion : [];
|
||||
}
|
||||
|
||||
String getSurveyQuestionIndex({required String questionTitle}) {
|
||||
return (state is! SurveyQuestionFetchSuccess) ? "0" : (state as SurveyQuestionFetchSuccess).surveyQuestion.where((element) => element.question == questionTitle).first.id!;
|
||||
}
|
||||
}
|
||||
92
news-app/lib/cubits/tagCubit.dart
Normal file
92
news-app/lib/cubits/tagCubit.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/TagModel.dart';
|
||||
import 'package:news/data/repositories/Tag/tagRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class TagState {}
|
||||
|
||||
class TagInitial extends TagState {}
|
||||
|
||||
class TagFetchInProgress extends TagState {}
|
||||
|
||||
class TagFetchSuccess extends TagState {
|
||||
final List<TagModel> tag;
|
||||
final int total;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
TagFetchSuccess(
|
||||
{required this.tag,
|
||||
required this.total,
|
||||
required this.hasMoreFetchError,
|
||||
required this.hasMore});
|
||||
}
|
||||
|
||||
class TagFetchFailure extends TagState {
|
||||
final String errorMessage;
|
||||
|
||||
TagFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class TagCubit extends Cubit<TagState> {
|
||||
final TagRepository _tagRepository;
|
||||
|
||||
TagCubit(this._tagRepository) : super(TagInitial());
|
||||
|
||||
void getTags({required String langId}) async {
|
||||
try {
|
||||
emit(TagFetchInProgress());
|
||||
final result = await _tagRepository.getTag(
|
||||
langId: langId, limit: limitOfAPIData.toString(), offset: "0");
|
||||
|
||||
emit(TagFetchSuccess(
|
||||
tag: result['Tag'],
|
||||
total: result[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: ((result['Tag'] as List<TagModel>).length < result[TOTAL])));
|
||||
} catch (e) {
|
||||
emit(TagFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
// Load tags if not already loaded or failed
|
||||
void loadIfFailed({required String langId}) {
|
||||
if (state is TagInitial || state is TagFetchFailure) {
|
||||
getTags(langId: langId);
|
||||
}
|
||||
}
|
||||
|
||||
void getMoreTags({required String langId}) async {
|
||||
if (state is TagFetchSuccess) {
|
||||
try {
|
||||
await _tagRepository
|
||||
.getTag(
|
||||
langId: langId,
|
||||
limit: limitOfAPIData.toString(),
|
||||
offset: (state as TagFetchSuccess).tag.length.toString())
|
||||
.then((value) {
|
||||
List<TagModel> updatedResults = (state as TagFetchSuccess).tag;
|
||||
updatedResults.addAll(value['Tag']);
|
||||
emit(TagFetchSuccess(
|
||||
tag: updatedResults,
|
||||
total: value[TOTAL],
|
||||
hasMoreFetchError: false,
|
||||
hasMore: (updatedResults.length < value[TOTAL])));
|
||||
});
|
||||
} catch (e) {
|
||||
emit(TagFetchSuccess(
|
||||
tag: (state as TagFetchSuccess).tag,
|
||||
total: (state as TagFetchSuccess).total,
|
||||
hasMoreFetchError: true,
|
||||
hasMore: (state as TagFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreTags() {
|
||||
return (state is TagFetchSuccess)
|
||||
? (state as TagFetchSuccess).hasMore
|
||||
: false;
|
||||
}
|
||||
}
|
||||
37
news-app/lib/cubits/tagNewsCubit.dart
Normal file
37
news-app/lib/cubits/tagNewsCubit.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/TagNews/tagNewsRepository.dart';
|
||||
|
||||
abstract class TagNewsState {}
|
||||
|
||||
class TagNewsInitial extends TagNewsState {}
|
||||
|
||||
class TagNewsFetchInProgress extends TagNewsState {}
|
||||
|
||||
class TagNewsFetchSuccess extends TagNewsState {
|
||||
final List<NewsModel> tagNews;
|
||||
|
||||
TagNewsFetchSuccess({required this.tagNews});
|
||||
}
|
||||
|
||||
class TagNewsFetchFailure extends TagNewsState {
|
||||
final String errorMessage;
|
||||
|
||||
TagNewsFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class TagNewsCubit extends Cubit<TagNewsState> {
|
||||
final TagNewsRepository _tagNewsRepository;
|
||||
|
||||
TagNewsCubit(this._tagNewsRepository) : super(TagNewsInitial());
|
||||
|
||||
void getTagNews({required String tagId, required String langId, String? latitude, String? longitude}) async {
|
||||
try {
|
||||
emit(TagNewsFetchInProgress());
|
||||
final result = await _tagNewsRepository.getTagNews(langId: langId, tagId: tagId, latitude: latitude, longitude: longitude);
|
||||
emit(TagNewsFetchSuccess(tagNews: result['TagNews']));
|
||||
} catch (e) {
|
||||
emit(TagNewsFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
21
news-app/lib/cubits/themeCubit.dart
Normal file
21
news-app/lib/cubits/themeCubit.dart
Normal file
@@ -0,0 +1,21 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/repositories/Settings/settingsLocalDataRepository.dart';
|
||||
|
||||
import 'package:news/ui/styles/appTheme.dart';
|
||||
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
|
||||
class ThemeState {
|
||||
final AppTheme appTheme;
|
||||
ThemeState(this.appTheme);
|
||||
}
|
||||
|
||||
class ThemeCubit extends Cubit<ThemeState> {
|
||||
SettingsLocalDataRepository settingsRepository;
|
||||
ThemeCubit(this.settingsRepository) : super(ThemeState(UiUtils.getAppThemeFromLabel(settingsRepository.getCurrentTheme())));
|
||||
|
||||
void changeTheme(AppTheme appTheme) {
|
||||
settingsRepository.setCurrentTheme(UiUtils.getThemeLabelFromAppTheme(appTheme));
|
||||
emit(ThemeState(appTheme));
|
||||
}
|
||||
}
|
||||
63
news-app/lib/cubits/updateBottomsheetContentCubit.dart
Normal file
63
news-app/lib/cubits/updateBottomsheetContentCubit.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/data/models/TagModel.dart';
|
||||
import 'package:news/data/models/appLanguageModel.dart';
|
||||
import 'package:news/data/models/locationCityModel.dart';
|
||||
|
||||
abstract class BottomSheetEvent {}
|
||||
|
||||
class UpdateBottomSheetContent extends BottomSheetEvent {
|
||||
final List<LocationCityModel> newData;
|
||||
final List<TagModel> newTagsData;
|
||||
final List<TagModel> newLanguagesData;
|
||||
|
||||
UpdateBottomSheetContent(this.newData, this.newTagsData, this.newLanguagesData);
|
||||
}
|
||||
|
||||
// Define the state for your bottom sheet Cubit
|
||||
class BottomSheetState {
|
||||
final List<LocationCityModel> locationData;
|
||||
final List<TagModel> tagsData;
|
||||
final List<LanguageModel> languageData;
|
||||
final List<CategoryModel> categoryData;
|
||||
|
||||
BottomSheetState(this.locationData, this.tagsData, this.languageData, this.categoryData);
|
||||
}
|
||||
|
||||
// Define the Cubit itself
|
||||
class BottomSheetCubit extends Cubit<BottomSheetState> {
|
||||
BottomSheetCubit() : super(BottomSheetState([], [], [], []));
|
||||
// Access the data field within the cubit
|
||||
|
||||
List<LocationCityModel> currentLocationData = [];
|
||||
List<TagModel> currentTagData = [];
|
||||
List<LanguageModel> currentLanguageData = [];
|
||||
List<CategoryModel> currentCategoryData = [];
|
||||
|
||||
getAllLatestContent({required bool isTag, required bool isLocation, required bool isLanguage, required bool isCategory}) {
|
||||
if (!isLocation) currentLocationData = state.locationData;
|
||||
if (!isTag) currentTagData = state.tagsData;
|
||||
if (!isLanguage) currentLanguageData = state.languageData;
|
||||
if (!isCategory) currentCategoryData = state.categoryData;
|
||||
}
|
||||
|
||||
void updateLocationContent(List<LocationCityModel> newData) {
|
||||
getAllLatestContent(isTag: false, isLocation: true, isLanguage: false, isCategory: false);
|
||||
emit(BottomSheetState(newData, currentTagData, currentLanguageData, currentCategoryData));
|
||||
}
|
||||
|
||||
void updateTagsContent(List<TagModel> newTagsData) {
|
||||
getAllLatestContent(isTag: true, isLocation: false, isLanguage: false, isCategory: false);
|
||||
emit(BottomSheetState(currentLocationData, newTagsData, currentLanguageData, currentCategoryData));
|
||||
}
|
||||
|
||||
void updateLanguageContent(List<LanguageModel> newLanguagesData) {
|
||||
getAllLatestContent(isTag: false, isLocation: false, isLanguage: true, isCategory: false);
|
||||
emit(BottomSheetState(currentLocationData, currentTagData, newLanguagesData, currentCategoryData));
|
||||
}
|
||||
|
||||
void updateCategoryContent(List<CategoryModel> newCategoryData) {
|
||||
getAllLatestContent(isTag: false, isLocation: false, isLanguage: false, isCategory: true);
|
||||
emit(BottomSheetState(currentLocationData, currentTagData, currentLanguageData, newCategoryData));
|
||||
}
|
||||
}
|
||||
63
news-app/lib/cubits/videosCubit.dart
Normal file
63
news-app/lib/cubits/videosCubit.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/Videos/videosRepository.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
abstract class VideoState {}
|
||||
|
||||
class VideoInitial extends VideoState {}
|
||||
|
||||
class VideoFetchInProgress extends VideoState {}
|
||||
|
||||
class VideoFetchSuccess extends VideoState {
|
||||
final List<NewsModel> video;
|
||||
final int totalVideoCount;
|
||||
final bool hasMoreFetchError;
|
||||
final bool hasMore;
|
||||
|
||||
VideoFetchSuccess({required this.video, required this.totalVideoCount, required this.hasMoreFetchError, required this.hasMore});
|
||||
}
|
||||
|
||||
class VideoFetchFailure extends VideoState {
|
||||
final String errorMessage;
|
||||
|
||||
VideoFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class VideoCubit extends Cubit<VideoState> {
|
||||
final VideoRepository _videoRepository;
|
||||
|
||||
VideoCubit(this._videoRepository) : super(VideoInitial());
|
||||
|
||||
void getVideo({required String langId, String? latitude, String? longitude}) async {
|
||||
try {
|
||||
emit(VideoFetchInProgress());
|
||||
final result = await _videoRepository.getVideo(limit: limitOfAPIData.toString(), offset: "0", langId: langId, latitude: latitude, longitude: longitude);
|
||||
(!result[ERROR])
|
||||
? emit(VideoFetchSuccess(video: result['Video'], totalVideoCount: result[TOTAL], hasMoreFetchError: false, hasMore: (result['Video'] as List<NewsModel>).length < result[TOTAL]))
|
||||
: emit(VideoFetchFailure(result[MESSAGE]));
|
||||
} catch (e) {
|
||||
emit(VideoFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
bool hasMoreVideo() {
|
||||
return (state is VideoFetchSuccess) ? (state as VideoFetchSuccess).hasMore : false;
|
||||
}
|
||||
|
||||
void getMoreVideo({required String langId, String? latitude, String? longitude}) async {
|
||||
if (state is VideoFetchSuccess) {
|
||||
try {
|
||||
final result =
|
||||
await _videoRepository.getVideo(langId: langId, limit: limitOfAPIData.toString(), offset: (state as VideoFetchSuccess).video.length.toString(), latitude: latitude, longitude: longitude);
|
||||
List<NewsModel> updatedResults = (state as VideoFetchSuccess).video;
|
||||
updatedResults.addAll(result['Video'] as List<NewsModel>);
|
||||
emit(VideoFetchSuccess(video: updatedResults, totalVideoCount: result[TOTAL], hasMoreFetchError: false, hasMore: updatedResults.length < result[TOTAL]));
|
||||
} catch (e) {
|
||||
emit(VideoFetchSuccess(
|
||||
video: (state as VideoFetchSuccess).video, hasMoreFetchError: true, totalVideoCount: (state as VideoFetchSuccess).totalVideoCount, hasMore: (state as VideoFetchSuccess).hasMore));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
41
news-app/lib/cubits/weatherCubit.dart
Normal file
41
news-app/lib/cubits/weatherCubit.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:news/data/models/WeatherData.dart';
|
||||
import 'package:news/utils/ErrorMessageKeys.dart';
|
||||
|
||||
abstract class WeatherState {}
|
||||
|
||||
class WeatherInitial extends WeatherState {}
|
||||
|
||||
class WeatherFetchInProgress extends WeatherState {}
|
||||
|
||||
class WeatherFetchSuccess extends WeatherState {
|
||||
final WeatherDetails weatherData;
|
||||
|
||||
WeatherFetchSuccess({required this.weatherData});
|
||||
}
|
||||
|
||||
class WeatherFetchFailure extends WeatherState {
|
||||
final String errorMessage;
|
||||
|
||||
WeatherFetchFailure(this.errorMessage);
|
||||
}
|
||||
|
||||
class WeatherCubit extends Cubit<WeatherState> {
|
||||
WeatherCubit() : super(WeatherInitial());
|
||||
|
||||
void getWeatherDetails({required String langId, String? lat, String? lon}) async {
|
||||
try {
|
||||
emit(WeatherFetchInProgress());
|
||||
|
||||
final weatherResponse = await Dio().get('https://api.weatherapi.com/v1/forecast.json?key=d0f2f4dbecc043e78d6123135212408&q=${lat.toString()},${lon.toString()}&days=1&alerts=no&lang=$langId');
|
||||
if (weatherResponse.statusCode == 200) {
|
||||
emit(WeatherFetchSuccess(weatherData: WeatherDetails.fromJson(Map.from(weatherResponse.data))));
|
||||
} else {
|
||||
emit(WeatherFetchFailure(weatherResponse.statusMessage ?? ErrorMessageKeys.defaultErrorMessage));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(WeatherFetchFailure(e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
124
news-app/lib/data/models/AppSystemSettingModel.dart
Normal file
124
news-app/lib/data/models/AppSystemSettingModel.dart
Normal file
@@ -0,0 +1,124 @@
|
||||
import 'package:news/data/models/appLanguageModel.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class AppSystemSettingModel {
|
||||
String? breakNewsMode, liveStreamMode, catMode, subCatMode, commentMode, inAppAdsMode, iosInAppAdsMode, adsType, iosAdsType;
|
||||
String? goRewardedId, goInterId, goBannerId, goNativeId;
|
||||
String? goIOSRewardedId, goIOSInterId, goIOSBannerId, goIOSNativeId;
|
||||
String? gameId, iosGameId;
|
||||
String? unityRewardedId, unityInterId, unityBannerId, unityIOSRewardedId, unityIOSInterId, unityIOSBannerId;
|
||||
String? locationWiseNewsMode, weatherMode, maintenanceMode, forceUpdateMode;
|
||||
LanguageModel? defaultLangDataModel;
|
||||
String? rssFeedMode, mobileLoginMode, countryCode, shareAppText, appstoreId, androidAppLink, iosAppLink;
|
||||
VideoViewType? videoTypePreference;
|
||||
String? androidAppVersion, iosAppVersion, googleGeminiApiKey;
|
||||
|
||||
AppSystemSettingModel(
|
||||
{this.breakNewsMode,
|
||||
this.liveStreamMode,
|
||||
this.catMode,
|
||||
this.subCatMode,
|
||||
this.commentMode,
|
||||
this.inAppAdsMode,
|
||||
this.iosInAppAdsMode,
|
||||
this.adsType,
|
||||
this.iosAdsType,
|
||||
this.goRewardedId,
|
||||
this.goBannerId,
|
||||
this.goInterId,
|
||||
this.goNativeId,
|
||||
this.goIOSBannerId,
|
||||
this.goIOSInterId,
|
||||
this.goIOSNativeId,
|
||||
this.goIOSRewardedId,
|
||||
this.gameId,
|
||||
this.iosGameId,
|
||||
this.unityRewardedId,
|
||||
this.unityInterId,
|
||||
this.unityBannerId,
|
||||
this.unityIOSRewardedId,
|
||||
this.unityIOSInterId,
|
||||
this.unityIOSBannerId,
|
||||
this.defaultLangDataModel,
|
||||
this.locationWiseNewsMode,
|
||||
this.weatherMode,
|
||||
this.maintenanceMode,
|
||||
this.rssFeedMode,
|
||||
this.mobileLoginMode,
|
||||
this.countryCode,
|
||||
this.shareAppText,
|
||||
this.appstoreId,
|
||||
this.androidAppLink,
|
||||
this.iosAppLink,
|
||||
this.videoTypePreference,
|
||||
this.forceUpdateMode,
|
||||
this.androidAppVersion,
|
||||
this.iosAppVersion,
|
||||
this.googleGeminiApiKey});
|
||||
|
||||
factory AppSystemSettingModel.fromJson(Map<String, dynamic> json) {
|
||||
var defaultList = (json[DEFAULT_LANG]);
|
||||
|
||||
LanguageModel defaultLangData;
|
||||
if (defaultList == null && defaultList.isEmpty) {
|
||||
defaultLangData = LanguageModel();
|
||||
} else {
|
||||
defaultLangData = LanguageModel.fromJson(defaultList);
|
||||
}
|
||||
|
||||
return AppSystemSettingModel(
|
||||
breakNewsMode: json[BREAK_NEWS_MODE],
|
||||
liveStreamMode: json[LIVE_STREAM_MODE],
|
||||
catMode: json[CATEGORY_MODE],
|
||||
subCatMode: json[SUBCAT_MODE],
|
||||
commentMode: json[COMM_MODE],
|
||||
inAppAdsMode: json[ADS_MODE],
|
||||
iosInAppAdsMode: json[IOS_ADS_MODE],
|
||||
adsType: json[ADS_TYPE],
|
||||
iosAdsType: json[IOS_ADS_TYPE],
|
||||
goRewardedId: json[GO_REWARDED_ID],
|
||||
goInterId: json[GO_INTER_ID],
|
||||
goBannerId: json[GO_BANNER_ID],
|
||||
goNativeId: json[GO_NATIVE_ID],
|
||||
goIOSRewardedId: json[IOS_GO_REWARDED_ID],
|
||||
goIOSNativeId: json[IOS_GO_NATIVE_ID],
|
||||
goIOSInterId: json[IOS_GO_INTER_ID],
|
||||
goIOSBannerId: json[IOS_GO_BANNER_ID],
|
||||
gameId: json[U_AND_GAME_ID],
|
||||
iosGameId: json[IOS_U_GAME_ID],
|
||||
unityRewardedId: json[U_REWARDED_ID],
|
||||
unityInterId: json[U_INTER_ID],
|
||||
unityBannerId: json[U_BANNER_ID],
|
||||
unityIOSRewardedId: json[IOS_U_REWARDED_ID],
|
||||
unityIOSInterId: json[IOS_U_INTER_ID],
|
||||
unityIOSBannerId: json[IOS_U_BANNER_ID],
|
||||
defaultLangDataModel: defaultLangData,
|
||||
locationWiseNewsMode: json[LOCATION_WISE_NEWS_MODE],
|
||||
weatherMode: json[WEATHER_MODE],
|
||||
maintenanceMode: json[MAINTENANCE_MODE],
|
||||
rssFeedMode: json[RSS_FEED_MODE],
|
||||
mobileLoginMode: json[MOBILE_LOGIN_MODE],
|
||||
countryCode: json[COUNTRY_CODE],
|
||||
shareAppText: json[SHARE_APP_TEXT],
|
||||
appstoreId: json[APPSTORE_ID],
|
||||
androidAppLink: json[WEB_SETTING][ANDROID_APP_LINK],
|
||||
iosAppLink: json[WEB_SETTING][IOS_APP_LINK],
|
||||
videoTypePreference: fromVideoTypeJson(json[VIDEO_TYPE_PREFERENCE]),
|
||||
forceUpdateMode: json[FORCE_UPDT_APP_MODE] ?? "0",
|
||||
androidAppVersion: json[ANDROID_APP_VERSION] ?? '',
|
||||
iosAppVersion: json[IOS_APP_VERSION] ?? '',
|
||||
googleGeminiApiKey: json[GEMINI_API_KEY]);
|
||||
}
|
||||
|
||||
static VideoViewType? fromVideoTypeJson(String? value) {
|
||||
switch (value) {
|
||||
case 'normal_style':
|
||||
return VideoViewType.normal;
|
||||
case 'page_style':
|
||||
return VideoViewType.page;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
34
news-app/lib/data/models/AuthModel.dart
Normal file
34
news-app/lib/data/models/AuthModel.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
import 'package:news/data/models/authorModel.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class AuthModel {
|
||||
String? id;
|
||||
String? name;
|
||||
String? email;
|
||||
String? mobile;
|
||||
String? profile;
|
||||
String? type;
|
||||
String? status;
|
||||
String? isFirstLogin; // 0 - new user, 1 - existing user
|
||||
String? role;
|
||||
String? jwtToken;
|
||||
int? isAuthor;
|
||||
Author? authorDetails;
|
||||
|
||||
AuthModel({this.id, this.name, this.email, this.mobile, this.profile, this.type, this.status, this.isFirstLogin, this.role, this.jwtToken, this.authorDetails, this.isAuthor = 0});
|
||||
|
||||
AuthModel.fromJson(Map<String, dynamic> json) {
|
||||
id = json[ID].toString();
|
||||
name = json[NAME] ?? "";
|
||||
email = json[EMAIL] ?? "";
|
||||
mobile = json[MOBILE] ?? "";
|
||||
profile = json[PROFILE] ?? "";
|
||||
type = json[TYPE] ?? "";
|
||||
status = json[STATUS].toString();
|
||||
isFirstLogin = (json[IS_LOGIN] != null) ? json[IS_LOGIN].toString() : "";
|
||||
role = json[ROLE].toString();
|
||||
jwtToken = json[TOKEN] ?? "";
|
||||
isAuthor = json[IS_AUTHOR];
|
||||
authorDetails = (isAuthor == 1 && json[AUTHOR] != null) ? Author.fromJson(json[AUTHOR]) : null;
|
||||
}
|
||||
}
|
||||
19
news-app/lib/data/models/BreakingNewsModel.dart
Normal file
19
news-app/lib/data/models/BreakingNewsModel.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class BreakingNewsModel {
|
||||
String? id, image, title, desc, contentType, contentValue, totalViews, slug;
|
||||
|
||||
BreakingNewsModel({this.id, this.image, this.title, this.desc, this.contentValue, this.contentType, this.totalViews, this.slug});
|
||||
|
||||
factory BreakingNewsModel.fromJson(Map<String, dynamic> json) {
|
||||
return BreakingNewsModel(
|
||||
id: json[ID].toString(),
|
||||
image: json[IMAGE],
|
||||
title: json[TITLE],
|
||||
desc: json[DESCRIPTION] ?? '',
|
||||
contentValue: json[CONTENT_VALUE],
|
||||
contentType: json[CONTENT_TYPE],
|
||||
totalViews: json[TOTAL_VIEWS].toString(),
|
||||
slug: json[SLUG]);
|
||||
}
|
||||
}
|
||||
26
news-app/lib/data/models/CategoryModel.dart
Normal file
26
news-app/lib/data/models/CategoryModel.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CategoryModel {
|
||||
String? id, image, categoryName;
|
||||
List<SubCategoryModel>? subData;
|
||||
|
||||
CategoryModel({this.id, this.image, this.categoryName, this.subData});
|
||||
|
||||
factory CategoryModel.fromJson(Map<String, dynamic> json) {
|
||||
var subList = (json.containsKey(SUBCATEGORIES)) ? (json[SUBCATEGORIES] as List) : [];
|
||||
List<SubCategoryModel> subCatData = [];
|
||||
subCatData = (subList.isEmpty) ? [] : subList.map((data) => SubCategoryModel.fromJson(data)).toList();
|
||||
|
||||
return CategoryModel(id: json[ID].toString(), image: json[IMAGE] ?? "", categoryName: json[CATEGORY_NAME], subData: subCatData);
|
||||
}
|
||||
}
|
||||
|
||||
class SubCategoryModel {
|
||||
String? id, categoryId, subCatName;
|
||||
|
||||
SubCategoryModel({this.id, this.categoryId, this.subCatName});
|
||||
|
||||
factory SubCategoryModel.fromJson(Map<String, dynamic> json) {
|
||||
return SubCategoryModel(id: json[ID].toString(), categoryId: json[CATEGORY_ID].toString(), subCatName: json[SUBCAT_NAME] ?? json[SUBCATEGORY]);
|
||||
}
|
||||
}
|
||||
60
news-app/lib/data/models/CommentModel.dart
Normal file
60
news-app/lib/data/models/CommentModel.dart
Normal file
@@ -0,0 +1,60 @@
|
||||
import 'package:news/data/models/AuthModel.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CommentModel {
|
||||
String? id, message, profile, date, name, status, like, dislike, totalLikes, totalDislikes, userId;
|
||||
List<ReplyModel>? replyComList;
|
||||
|
||||
CommentModel({this.id, this.message, this.profile, this.date, this.name, this.replyComList, this.status, this.like, this.dislike, this.totalLikes, this.totalDislikes, this.userId});
|
||||
|
||||
factory CommentModel.fromJson(Map<String, dynamic> json) {
|
||||
var replyList = (json[REPLY] as List);
|
||||
List<ReplyModel> replyData = [];
|
||||
if (replyList.isEmpty) {
|
||||
replyList = [];
|
||||
} else {
|
||||
replyData = replyList.map((data) => ReplyModel.fromJson(data)).toList();
|
||||
}
|
||||
|
||||
var userDetails = AuthModel.fromJson(json[USER]);
|
||||
|
||||
return CommentModel(
|
||||
id: json[ID].toString(),
|
||||
message: json[MESSAGE],
|
||||
profile: userDetails.profile,
|
||||
name: userDetails.name,
|
||||
date: json[DATE],
|
||||
status: json[STATUS].toString(),
|
||||
replyComList: replyData,
|
||||
like: json[LIKE].toString(),
|
||||
dislike: json[DISLIKE].toString(),
|
||||
totalDislikes: json[TOTAL_DISLIKE].toString(),
|
||||
totalLikes: json[TOTAL_LIKE].toString(),
|
||||
userId: json[USER_ID].toString());
|
||||
}
|
||||
}
|
||||
|
||||
class ReplyModel {
|
||||
String? id, message, profile, date, name, userId, parentId, newsId, status, like, dislike, totalLikes, totalDislikes;
|
||||
|
||||
ReplyModel({this.id, this.message, this.profile, this.date, this.name, this.userId, this.parentId, this.status, this.newsId, this.like, this.dislike, this.totalLikes, this.totalDislikes});
|
||||
|
||||
factory ReplyModel.fromJson(Map<String, dynamic> json) {
|
||||
var userDetails = AuthModel.fromJson(json[USER]);
|
||||
|
||||
return ReplyModel(
|
||||
id: json[ID].toString(),
|
||||
message: json[MESSAGE],
|
||||
profile: userDetails.profile,
|
||||
name: userDetails.name,
|
||||
date: json[DATE],
|
||||
userId: json[USER_ID].toString(),
|
||||
parentId: json[PARENT_ID].toString(),
|
||||
newsId: json[NEWS_ID].toString(),
|
||||
status: json[STATUS].toString(),
|
||||
like: json[LIKE].toString(),
|
||||
dislike: json[DISLIKE].toString(),
|
||||
totalDislikes: json[TOTAL_DISLIKE].toString(),
|
||||
totalLikes: json[TOTAL_LIKE].toString());
|
||||
}
|
||||
}
|
||||
97
news-app/lib/data/models/FeatureSectionModel.dart
Normal file
97
news-app/lib/data/models/FeatureSectionModel.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import 'package:news/data/models/BreakingNewsModel.dart';
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/models/adSpaceModel.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class FeatureSectionModel {
|
||||
String? id, languageId, title, shortDescription, newsType, videosType, categoryIds, subcategoryIds, newsIds, styleApp, createdAt, status, summarizedDesc;
|
||||
int? newsTotal, breakNewsTotal, videosTotal;
|
||||
List<NewsModel>? news;
|
||||
List<BreakingNewsModel>? breakNews, breakVideos;
|
||||
List<NewsModel>? videos;
|
||||
AdSpaceModel? adSpaceDetails;
|
||||
|
||||
FeatureSectionModel(
|
||||
{this.id,
|
||||
this.languageId,
|
||||
this.title,
|
||||
this.shortDescription,
|
||||
this.newsType,
|
||||
this.videosType,
|
||||
this.categoryIds,
|
||||
this.subcategoryIds,
|
||||
this.newsIds,
|
||||
this.styleApp,
|
||||
this.createdAt,
|
||||
this.newsTotal,
|
||||
this.breakNewsTotal,
|
||||
this.videosTotal,
|
||||
this.news,
|
||||
this.breakNews,
|
||||
this.videos,
|
||||
this.breakVideos,
|
||||
this.adSpaceDetails,
|
||||
this.summarizedDesc});
|
||||
|
||||
factory FeatureSectionModel.fromJson(Map<String, dynamic> json) {
|
||||
List<NewsModel> newsData = [];
|
||||
if (json.containsKey(NEWS)) {
|
||||
var newsList = (json[NEWS] as List);
|
||||
if (newsList.isEmpty) {
|
||||
newsList = [];
|
||||
} else {
|
||||
newsData = newsList.map((data) => NewsModel.fromJson(data)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
List<BreakingNewsModel> breakNewsData = [];
|
||||
if (json.containsKey(BREAKING_NEWS)) {
|
||||
var breakNewsList = (json[BREAKING_NEWS] as List);
|
||||
if (breakNewsList.isEmpty) {
|
||||
breakNewsList = [];
|
||||
} else {
|
||||
breakNewsData = breakNewsList.map((data) => BreakingNewsModel.fromJson(data)).toList();
|
||||
}
|
||||
}
|
||||
|
||||
List<NewsModel> videosData = [];
|
||||
List<BreakingNewsModel> breakVideosData = [];
|
||||
if (json.containsKey(VIDEOS)) {
|
||||
var videosList = (json[VIDEOS] as List);
|
||||
if (videosList.isEmpty) {
|
||||
videosList = [];
|
||||
} else {
|
||||
if (json[VIDEOS_TYPE] == 'news') {
|
||||
videosData = videosList.map((data) => NewsModel.fromVideos(data)).toList();
|
||||
} else {
|
||||
breakVideosData = videosList.map((data) => BreakingNewsModel.fromJson(data)).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
AdSpaceModel? adSpaceData;
|
||||
if (json.containsKey(AD_SPACES)) {
|
||||
adSpaceData = AdSpaceModel.fromJson(json[AD_SPACES]);
|
||||
}
|
||||
|
||||
return FeatureSectionModel(
|
||||
id: json[ID].toString(),
|
||||
languageId: json[LANGUAGE_ID].toString(),
|
||||
title: json[TITLE],
|
||||
shortDescription: json[SHORT_DESC],
|
||||
newsType: json[NEWS_TYPE],
|
||||
videosType: json[VIDEOS_TYPE],
|
||||
categoryIds: json[CAT_IDS],
|
||||
subcategoryIds: json[SUBCAT_IDS],
|
||||
newsIds: json[NEWS_IDS],
|
||||
styleApp: json[STYLE_APP],
|
||||
newsTotal: json[NEWS_TOTAL],
|
||||
breakNewsTotal: json[BREAK_NEWS_TOTAL],
|
||||
videosTotal: json[VIDEOS_TOTAL],
|
||||
summarizedDesc: json[SUMM_DESCRIPTION],
|
||||
news: newsData,
|
||||
breakNews: breakNewsData,
|
||||
videos: videosData,
|
||||
breakVideos: breakVideosData,
|
||||
adSpaceDetails: adSpaceData);
|
||||
}
|
||||
}
|
||||
11
news-app/lib/data/models/LiveStreamingModel.dart
Normal file
11
news-app/lib/data/models/LiveStreamingModel.dart
Normal file
@@ -0,0 +1,11 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class LiveStreamingModel {
|
||||
String? id, image, title, type, url, updatedDate;
|
||||
|
||||
LiveStreamingModel({this.id, this.image, this.title, this.type, this.url, this.updatedDate});
|
||||
|
||||
factory LiveStreamingModel.fromJson(Map<String, dynamic> json) {
|
||||
return LiveStreamingModel(id: json[ID].toString(), image: json[IMAGE], title: json[TITLE], type: json[TYPE], url: json[URL], updatedDate: json[UPDATED_DATE]);
|
||||
}
|
||||
}
|
||||
196
news-app/lib/data/models/NewsModel.dart
Normal file
196
news-app/lib/data/models/NewsModel.dart
Normal file
@@ -0,0 +1,196 @@
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/data/models/authorModel.dart';
|
||||
import 'package:news/data/models/locationCityModel.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
import 'package:news/data/models/OptionModel.dart';
|
||||
|
||||
class NewsModel {
|
||||
String? id, userId, newsId, categoryId, title, date, contentType, contentValue, image, desc, categoryName, dateSent, totalLikes, like, shortDesc;
|
||||
String? bookmark, keyName, tagId, tagName, subCatId, img, subCatName, showTill, langId, totalViews, locationId, locationName, metaKeyword, metaTitle, metaDescription, slug, publishDate;
|
||||
|
||||
List<ImageDataModel>? imageDataList;
|
||||
|
||||
bool? history = false;
|
||||
String? question, status, type, sourceType;
|
||||
List<OptionModel>? optionDataList;
|
||||
int? from, isExpired, isCommentEnabled;
|
||||
Author? authorDetails;
|
||||
UserAuthorModel? userAthorDetails;
|
||||
|
||||
NewsModel(
|
||||
{this.id,
|
||||
this.userId,
|
||||
this.newsId,
|
||||
this.categoryId,
|
||||
this.title,
|
||||
this.date,
|
||||
this.contentType,
|
||||
this.contentValue,
|
||||
this.image,
|
||||
this.desc,
|
||||
this.categoryName,
|
||||
this.dateSent,
|
||||
this.imageDataList,
|
||||
this.totalLikes,
|
||||
this.like,
|
||||
this.keyName,
|
||||
this.tagName,
|
||||
this.subCatId,
|
||||
this.tagId,
|
||||
this.history,
|
||||
this.optionDataList,
|
||||
this.question,
|
||||
this.status,
|
||||
this.type,
|
||||
this.from,
|
||||
this.img,
|
||||
this.subCatName,
|
||||
this.showTill,
|
||||
this.bookmark,
|
||||
this.langId,
|
||||
this.totalViews,
|
||||
this.locationId,
|
||||
this.locationName,
|
||||
this.metaTitle,
|
||||
this.metaDescription,
|
||||
this.metaKeyword,
|
||||
this.slug,
|
||||
this.publishDate,
|
||||
this.isExpired,
|
||||
this.isCommentEnabled,
|
||||
this.sourceType,
|
||||
this.shortDesc,
|
||||
this.authorDetails,
|
||||
this.userAthorDetails});
|
||||
|
||||
factory NewsModel.history(String history) {
|
||||
return NewsModel(title: history, history: true);
|
||||
}
|
||||
|
||||
factory NewsModel.fromSurvey(Map<String, dynamic> json) {
|
||||
List<OptionModel> optionList = (json[OPTION] as List).map((data) => OptionModel.fromJson(data)).toList();
|
||||
|
||||
return NewsModel(id: json[ID].toString(), question: json[QUESTION], status: json[STATUS].toString(), optionDataList: optionList, type: "survey", from: 1);
|
||||
}
|
||||
|
||||
factory NewsModel.fromVideos(Map<String, dynamic> json) {
|
||||
String? tagName;
|
||||
|
||||
tagName = (json[TAG] == null) ? "" : json[TAG];
|
||||
return NewsModel(
|
||||
id: json[ID].toString(),
|
||||
newsId: json[ID].toString(),
|
||||
//for bookmark get/set
|
||||
desc: json[DESCRIPTION] ?? '',
|
||||
date: json[DATE],
|
||||
image: json[IMAGE],
|
||||
title: json[TITLE],
|
||||
contentType: json[CONTENT_TYPE],
|
||||
contentValue: json[CONTENT_VALUE],
|
||||
tagId: json[TAG_ID],
|
||||
tagName: tagName,
|
||||
categoryName: json[CATEGORY_NAME] ?? '',
|
||||
sourceType: json[SOURCE_TYPE],
|
||||
shortDesc: json[SUMM_DESCRIPTION] ?? '');
|
||||
}
|
||||
|
||||
factory NewsModel.fromJson(Map<String, dynamic> json) {
|
||||
bool isAuthor = (json[USER] == null) ? false : (json[USER][IS_AUTHOR] == 1);
|
||||
|
||||
String? tagName;
|
||||
|
||||
tagName = (json[TAG] == null) ? "" : json[TAG];
|
||||
|
||||
List<ImageDataModel> imageData = [];
|
||||
var imageList = (json.containsKey(IMAGES))
|
||||
? json[IMAGES] as List<dynamic>
|
||||
: (json.containsKey(IMAGE_DATA))
|
||||
? json[IMAGE_DATA] as List
|
||||
: [];
|
||||
imageList = (imageList.isEmpty) ? [] : imageList.map((data) => ImageDataModel.fromJson(data)).toList();
|
||||
if (imageList.isNotEmpty) imageData = imageList as List<ImageDataModel>;
|
||||
var categoryName = '';
|
||||
try {
|
||||
categoryName = (json.containsKey(CATEGORY_NAME))
|
||||
? json[CATEGORY_NAME]
|
||||
: (json.containsKey(CATEGORY))
|
||||
? CategoryModel.fromJson(json[CATEGORY]).categoryName
|
||||
: '';
|
||||
} catch (e) {}
|
||||
|
||||
var subcategoryName =
|
||||
(json.containsKey(SUBCAT_NAME)) ? json[SUBCAT_NAME] : ((json.containsKey(SUBCATEGORY) && json[SUBCATEGORY] != null) ? SubCategoryModel.fromJson(json[SUBCATEGORY]).subCatName : '');
|
||||
|
||||
return NewsModel(
|
||||
id: json[ID].toString(),
|
||||
userId: json[USER_ID].toString(),
|
||||
newsId: (json[NEWS_ID] != null && json[NEWS_ID].toString().trim().isNotEmpty) ? json[NEWS_ID].toString() : json[ID].toString(),
|
||||
//incase of null newsId in Response
|
||||
categoryId: json[CATEGORY_ID].toString(),
|
||||
title: json[TITLE],
|
||||
date: json[DATE],
|
||||
contentType: json[CONTENT_TYPE],
|
||||
contentValue: json[CONTENT_VALUE],
|
||||
image: json[IMAGE],
|
||||
desc: json[DESCRIPTION] ?? '',
|
||||
categoryName: categoryName,
|
||||
dateSent: json[DATE_SENT],
|
||||
imageDataList: imageData,
|
||||
totalLikes: json[TOTAL_LIKE].toString(),
|
||||
like: json[LIKE].toString(),
|
||||
bookmark: json[BOOKMARK].toString(),
|
||||
tagId: json[TAG_ID],
|
||||
tagName: tagName,
|
||||
subCatId: json[SUBCAT_ID].toString(),
|
||||
history: false,
|
||||
type: "news",
|
||||
img: "",
|
||||
subCatName: subcategoryName,
|
||||
showTill: json[SHOW_TILL],
|
||||
langId: json[LANGUAGE_ID].toString(),
|
||||
totalViews: json[TOTAL_VIEWS].toString(),
|
||||
locationId: (json.containsKey(LOCATION) && json[LOCATION] != null) ? LocationCityModel.fromJson(json[LOCATION]).id.toString() : json[LOCATION_ID].toString(),
|
||||
locationName: (json.containsKey(LOCATION) && json[LOCATION] != null) ? LocationCityModel.fromJson(json[LOCATION]).locationName : json[LOCATION_NAME],
|
||||
metaKeyword: json[META_KEYWORD],
|
||||
metaTitle: json[META_TITLE],
|
||||
metaDescription: json[META_DESC],
|
||||
slug: json[SLUG],
|
||||
publishDate: json[PUBLISHED_DATE],
|
||||
isExpired: json[IS_EXPIRED] ?? 0,
|
||||
status: json[STATUS].toString(),
|
||||
isCommentEnabled: json[IS_COMMENT_ENABLED] ?? 1,
|
||||
shortDesc: json[SUMM_DESCRIPTION] ?? '',
|
||||
userAthorDetails: (json[USER] == null) ? null : UserAuthorModel.fromJson(json[USER]),
|
||||
authorDetails: (isAuthor && json[AUTHOR] != null) ? Author.fromJson(json[AUTHOR]) : null);
|
||||
}
|
||||
}
|
||||
|
||||
class ImageDataModel {
|
||||
String? id;
|
||||
String? otherImage;
|
||||
|
||||
ImageDataModel({this.otherImage, this.id});
|
||||
|
||||
factory ImageDataModel.fromJson(Map<String, dynamic> json) {
|
||||
return ImageDataModel(otherImage: json[OTHER_IMAGE], id: json[ID].toString());
|
||||
}
|
||||
}
|
||||
|
||||
class UserAuthorModel {
|
||||
String? id;
|
||||
String? name;
|
||||
String? profile;
|
||||
int? isAuthor;
|
||||
Author? authorData;
|
||||
|
||||
UserAuthorModel({this.id, this.name, this.profile, this.isAuthor, this.authorData});
|
||||
|
||||
factory UserAuthorModel.fromJson(Map<String, dynamic> json) {
|
||||
return UserAuthorModel(
|
||||
id: json[ID].toString(),
|
||||
name: json[NAME],
|
||||
profile: json[PROFILE].toString(),
|
||||
isAuthor: json[IS_AUTHOR] ?? 0,
|
||||
authorData: (json.containsKey(AUTHOR) && json[AUTHOR] != null) ? Author.fromJson(json[AUTHOR]) : null);
|
||||
}
|
||||
}
|
||||
20
news-app/lib/data/models/OptionModel.dart
Normal file
20
news-app/lib/data/models/OptionModel.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class OptionModel {
|
||||
String? id;
|
||||
String? options;
|
||||
String? counter;
|
||||
double? percentage;
|
||||
String? questionId;
|
||||
|
||||
OptionModel({this.id, this.options, this.counter, this.percentage, this.questionId});
|
||||
|
||||
factory OptionModel.fromJson(Map<String, dynamic> json) {
|
||||
return OptionModel(
|
||||
id: json[ID].toString(),
|
||||
options: json[OPTIONS],
|
||||
counter: json[COUNTER].toString(),
|
||||
percentage: (json[PERCENTAGE].runtimeType == int) ? double.parse(json[PERCENTAGE].toString()) : json[PERCENTAGE],
|
||||
questionId: json[QUESTION_ID].toString());
|
||||
}
|
||||
}
|
||||
15
news-app/lib/data/models/OtherPageModel.dart
Normal file
15
news-app/lib/data/models/OtherPageModel.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class OtherPageModel {
|
||||
String? id, pageContent, title, image;
|
||||
//slug,meta_description,meta_keywords not in use.
|
||||
OtherPageModel({this.id, this.pageContent, this.title, this.image});
|
||||
|
||||
factory OtherPageModel.fromJson(Map<String, dynamic> json) {
|
||||
return OtherPageModel(id: json[ID].toString(), pageContent: json[PAGE_CONTENT], title: json[TITLE], image: json[PAGE_ICON]);
|
||||
}
|
||||
|
||||
factory OtherPageModel.fromPrivacyTermsJson(Map<String, dynamic> json) {
|
||||
return OtherPageModel(id: json[ID].toString().toString(), pageContent: json[PAGE_CONTENT], title: json[TITLE]);
|
||||
}
|
||||
}
|
||||
23
news-app/lib/data/models/RSSFeedModel.dart
Normal file
23
news-app/lib/data/models/RSSFeedModel.dart
Normal file
@@ -0,0 +1,23 @@
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class RSSFeedModel {
|
||||
String? id, feedName, feedUrl, categoryId, categoryName, subCatName, tagName;
|
||||
|
||||
RSSFeedModel({this.id, this.feedName, this.feedUrl, this.categoryId, this.tagName, this.categoryName, this.subCatName});
|
||||
|
||||
factory RSSFeedModel.fromJson(Map<String, dynamic> json) {
|
||||
String? tagName;
|
||||
|
||||
tagName = (json[TAG] == null) ? "" : json[TAG];
|
||||
var categoryName = (json.containsKey(CATEGORY_NAME))
|
||||
? json[CATEGORY_NAME]
|
||||
: (json.containsKey(CATEGORY) && (json[CATEGORY] != null))
|
||||
? CategoryModel.fromJson(json[CATEGORY]).categoryName
|
||||
: '';
|
||||
var subcategoryName =
|
||||
(json.containsKey(SUBCAT_NAME)) ? json[SUBCAT_NAME] : ((json.containsKey(SUBCATEGORY) && json[SUBCATEGORY] != null) ? SubCategoryModel.fromJson(json[SUBCATEGORY]).subCatName : '');
|
||||
|
||||
return RSSFeedModel(id: json[ID].toString(), feedName: json[FEED_NAME].toString(), feedUrl: json[FEED_URL], tagName: tagName, categoryName: categoryName, subCatName: subcategoryName);
|
||||
}
|
||||
}
|
||||
42
news-app/lib/data/models/SettingsModel.dart
Normal file
42
news-app/lib/data/models/SettingsModel.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
class SettingsModel {
|
||||
bool showIntroSlider;
|
||||
bool notification;
|
||||
String languageCode;
|
||||
String theme;
|
||||
String token;
|
||||
|
||||
SettingsModel({
|
||||
required this.languageCode,
|
||||
required this.showIntroSlider,
|
||||
required this.theme,
|
||||
required this.notification,
|
||||
required this.token,
|
||||
});
|
||||
|
||||
static SettingsModel fromJson(var settingsJson) {
|
||||
//to see the json response go to getCurrentSettings() function in settingsRepository
|
||||
return SettingsModel(
|
||||
theme: settingsJson['theme'],
|
||||
showIntroSlider: settingsJson['showIntroSlider'],
|
||||
notification: settingsJson['notification'],
|
||||
languageCode: settingsJson['languageCode'],
|
||||
token: settingsJson['token'],
|
||||
);
|
||||
}
|
||||
|
||||
SettingsModel copyWith({
|
||||
String? theme,
|
||||
bool? showIntroSlider,
|
||||
bool? notification,
|
||||
String? languageCode,
|
||||
String? token,
|
||||
}) {
|
||||
return SettingsModel(
|
||||
theme: theme ?? this.theme,
|
||||
notification: notification ?? this.notification,
|
||||
showIntroSlider: showIntroSlider ?? this.showIntroSlider,
|
||||
languageCode: languageCode ?? this.languageCode,
|
||||
token: token ?? this.token,
|
||||
);
|
||||
}
|
||||
}
|
||||
11
news-app/lib/data/models/TagModel.dart
Normal file
11
news-app/lib/data/models/TagModel.dart
Normal file
@@ -0,0 +1,11 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class TagModel {
|
||||
String? id, tagName;
|
||||
|
||||
TagModel({this.id, this.tagName});
|
||||
|
||||
factory TagModel.fromJson(Map<String, dynamic> json) {
|
||||
return TagModel(id: json[ID].toString(), tagName: json[TAGNAME]);
|
||||
}
|
||||
}
|
||||
24
news-app/lib/data/models/WeatherData.dart
Normal file
24
news-app/lib/data/models/WeatherData.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
class WeatherDetails {
|
||||
String? name;
|
||||
String? region;
|
||||
double? tempC;
|
||||
String? text;
|
||||
String? icon;
|
||||
double? minTempC;
|
||||
double? maxTempC;
|
||||
String? country;
|
||||
|
||||
WeatherDetails({this.name, this.region, this.tempC, this.text, this.icon, this.maxTempC, this.minTempC, this.country});
|
||||
|
||||
factory WeatherDetails.fromJson(Map<String, dynamic> json) {
|
||||
return WeatherDetails(
|
||||
name: json["location"]["name"],
|
||||
region: json["location"]["region"],
|
||||
country: json["location"]["country"],
|
||||
tempC: json["current"]["temp_c"],
|
||||
text: json["current"]["condition"]["text"],
|
||||
icon: json["current"]["condition"]["icon"],
|
||||
maxTempC: json["forecast"]["forecastday"][0]["day"]["maxtemp_c"],
|
||||
minTempC: json["forecast"]["forecastday"][0]["day"]["mintemp_c"]);
|
||||
}
|
||||
}
|
||||
13
news-app/lib/data/models/adSpaceModel.dart
Normal file
13
news-app/lib/data/models/adSpaceModel.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class AdSpaceModel {
|
||||
String? id, adSpace, adFeaturedSectionId, adImage, adUrl;
|
||||
|
||||
AdSpaceModel({this.id, this.adSpace, this.adFeaturedSectionId, this.adImage, this.adUrl});
|
||||
|
||||
//place Ad just above mentioned adFeaturedSectionId
|
||||
|
||||
factory AdSpaceModel.fromJson(Map<String, dynamic> json) {
|
||||
return AdSpaceModel(id: json[ID].toString(), adSpace: json[AD_SPACE], adFeaturedSectionId: json[AD_FEATURED_SECTION_ID].toString(), adImage: json[AD_IMAGE], adUrl: json[AD_URL]);
|
||||
}
|
||||
}
|
||||
16
news-app/lib/data/models/appLanguageModel.dart
Normal file
16
news-app/lib/data/models/appLanguageModel.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class LanguageModel {
|
||||
String? id, language, languageDisplayName, image, code;
|
||||
int? isRTL;
|
||||
LanguageModel({this.id, this.image, this.language, this.languageDisplayName, this.code, this.isRTL});
|
||||
factory LanguageModel.fromJson(Map<String, dynamic> json) {
|
||||
return LanguageModel(
|
||||
id: json[ID].toString(),
|
||||
image: json[IMAGE],
|
||||
language: json[LANGUAGE],
|
||||
languageDisplayName: (json[DISPLAY_NAME_LANG] != "") ? json[DISPLAY_NAME_LANG] : json[LANGUAGE],
|
||||
code: json[CODE],
|
||||
isRTL: (json[ISRTL].runtimeType == int) ? json[ISRTL] : int.tryParse(json[ISRTL]));
|
||||
}
|
||||
}
|
||||
49
news-app/lib/data/models/authorModel.dart
Normal file
49
news-app/lib/data/models/authorModel.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class Author {
|
||||
final int? id;
|
||||
final int? userId;
|
||||
final String? bio;
|
||||
final String? telegramLink;
|
||||
final String? linkedinLink;
|
||||
final String? facebookLink;
|
||||
final String? whatsappLink;
|
||||
final AuthorStatus? status;
|
||||
|
||||
Author({
|
||||
this.id,
|
||||
this.userId,
|
||||
this.bio,
|
||||
this.telegramLink,
|
||||
this.linkedinLink,
|
||||
this.facebookLink,
|
||||
this.whatsappLink,
|
||||
this.status,
|
||||
});
|
||||
|
||||
factory Author.fromJson(Map<String, dynamic> json) {
|
||||
return Author(
|
||||
id: json['id'] as int?,
|
||||
userId: json['user_id'] as int?,
|
||||
bio: json['bio'] ?? "",
|
||||
telegramLink: json['telegram_link'] ?? "",
|
||||
linkedinLink: json['linkedin_link'] ?? "",
|
||||
facebookLink: json['facebook_link'] ?? "",
|
||||
whatsappLink: json['whatsapp_link'] ?? "",
|
||||
status: fromAuthorStatus(json[STATUS]));
|
||||
}
|
||||
}
|
||||
|
||||
AuthorStatus? fromAuthorStatus(String? value) {
|
||||
switch (value) {
|
||||
case 'pending':
|
||||
return AuthorStatus.pending;
|
||||
case 'approved':
|
||||
return AuthorStatus.approved;
|
||||
case 'rejected':
|
||||
return AuthorStatus.rejected;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
14
news-app/lib/data/models/locationCityModel.dart
Normal file
14
news-app/lib/data/models/locationCityModel.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class LocationCityModel {
|
||||
final String id;
|
||||
final String locationName;
|
||||
final String latitude;
|
||||
final String longitude;
|
||||
|
||||
LocationCityModel({required this.latitude, required this.longitude, required this.id, required this.locationName});
|
||||
|
||||
factory LocationCityModel.fromJson(Map<String, dynamic> json) {
|
||||
return LocationCityModel(id: json[ID].toString(), locationName: json[LOCATION_NAME], latitude: json[LATITUDE].toString(), longitude: json[LONGITUDE].toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:io';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class AddNewsRemoteDataSource {
|
||||
//to update fcmId of user's
|
||||
Future<dynamic> addNewsData(
|
||||
{required BuildContext context,
|
||||
required String actionType,
|
||||
required String catId,
|
||||
required String title,
|
||||
required String conTypeId,
|
||||
required String conType,
|
||||
required String langId,
|
||||
File? image,
|
||||
String? newsId,
|
||||
String? subCatId,
|
||||
String? showTill,
|
||||
String? tagId,
|
||||
String? url,
|
||||
String? desc,
|
||||
String? summDescription,
|
||||
String? locationId,
|
||||
File? videoUpload,
|
||||
List<File>? otherImage,
|
||||
String? publishDate,
|
||||
required String metaTitle,
|
||||
required String metaDescription,
|
||||
required String metaKeyword,
|
||||
required String slug,
|
||||
required int isDraft}) async {
|
||||
try {
|
||||
Map<String, dynamic> body = {
|
||||
ACTION_TYPE: actionType,
|
||||
CATEGORY_ID: catId,
|
||||
TITLE: title,
|
||||
CONTENT_TYPE: conTypeId,
|
||||
LANGUAGE_ID: langId,
|
||||
META_TITLE: metaTitle,
|
||||
META_DESC: metaDescription,
|
||||
META_KEYWORD: metaKeyword,
|
||||
SLUG: slug,
|
||||
SUMM_DESCRIPTION: summDescription,
|
||||
IS_DRAFT_KEY: isDraft
|
||||
};
|
||||
Map<String, dynamic> result = {};
|
||||
|
||||
if (image != null) body[IMAGE] = await MultipartFile.fromFile(image.path);
|
||||
if (newsId != null) body[NEWS_ID] = newsId; // in case of update news only
|
||||
if (subCatId != null) body[SUBCAT_ID] = subCatId;
|
||||
if (showTill != null) body[SHOW_TILL] = showTill;
|
||||
if (tagId != null) body[TAG_ID] = tagId;
|
||||
if (desc != null) body[DESCRIPTION] = desc;
|
||||
if (locationId != null) body[LOCATION_ID] = locationId;
|
||||
if (publishDate != null) body[PUBLISHED_DATE] = publishDate;
|
||||
|
||||
if (url != null && (conType == UiUtils.getTranslatedLabel(context, 'videoOtherUrlLbl') || conType == UiUtils.getTranslatedLabel(context, 'videoYoutubeLbl'))) {
|
||||
body[CONTENT_DATA] = url;
|
||||
} else if (conType == UiUtils.getTranslatedLabel(context, 'videoUploadLbl')) {
|
||||
if (videoUpload != null) body[CONTENT_DATA] = await MultipartFile.fromFile(videoUpload.path);
|
||||
}
|
||||
|
||||
if (otherImage!.isNotEmpty) {
|
||||
for (var i = 0; i < otherImage.length; i++) {
|
||||
body["ofile[$i]"] = await MultipartFile.fromFile(otherImage[i].path);
|
||||
}
|
||||
}
|
||||
|
||||
result = await Api.sendApiRequest(body: body, url: Api.setNewsApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:news/data/repositories/AddNews/addNewsRemoteDataSource.dart';
|
||||
|
||||
class AddNewsRepository {
|
||||
static final AddNewsRepository _addNewsRepository = AddNewsRepository._internal();
|
||||
|
||||
late AddNewsRemoteDataSource _addNewsRemoteDataSource;
|
||||
|
||||
factory AddNewsRepository() {
|
||||
_addNewsRepository._addNewsRemoteDataSource = AddNewsRemoteDataSource();
|
||||
return _addNewsRepository;
|
||||
}
|
||||
|
||||
AddNewsRepository._internal();
|
||||
|
||||
Future<Map<String, dynamic>> addNews(
|
||||
{required BuildContext context,
|
||||
required String actionType,
|
||||
required String catId,
|
||||
required String title,
|
||||
required String conTypeId,
|
||||
required String conType,
|
||||
required String langId,
|
||||
File? image,
|
||||
String? newsId,
|
||||
String? subCatId,
|
||||
String? showTill,
|
||||
String? tagId,
|
||||
String? url,
|
||||
String? desc,
|
||||
String? summDescription,
|
||||
String? locationId,
|
||||
File? videoUpload,
|
||||
List<File>? otherImage,
|
||||
String? publishDate,
|
||||
required String metaTitle,
|
||||
required String metaDescription,
|
||||
required String metaKeyword,
|
||||
required String slug,
|
||||
required int isDraft}) async {
|
||||
final result = await _addNewsRemoteDataSource.addNewsData(
|
||||
context: context,
|
||||
actionType: actionType,
|
||||
newsId: newsId,
|
||||
catId: catId,
|
||||
langId: langId,
|
||||
conType: conType,
|
||||
conTypeId: conTypeId,
|
||||
image: image,
|
||||
title: title,
|
||||
subCatId: subCatId,
|
||||
showTill: showTill,
|
||||
desc: desc,
|
||||
otherImage: otherImage,
|
||||
tagId: tagId,
|
||||
url: url,
|
||||
videoUpload: videoUpload,
|
||||
locationId: locationId,
|
||||
metaTitle: metaTitle,
|
||||
metaDescription: metaDescription,
|
||||
metaKeyword: metaKeyword,
|
||||
slug: slug,
|
||||
publishDate: publishDate ?? null,
|
||||
summDescription: summDescription,
|
||||
isDraft: isDraft);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class SystemRepository {
|
||||
Future<dynamic> fetchSettings() async {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(url: Api.getSettingApi, body: null, isGet: true);
|
||||
return result[DATA];
|
||||
} catch (e) {
|
||||
throw ApiException(e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
119
news-app/lib/data/repositories/Auth/authLocalDataSource.dart
Normal file
119
news-app/lib/data/repositories/Auth/authLocalDataSource.dart
Normal file
@@ -0,0 +1,119 @@
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/hiveBoxKeys.dart';
|
||||
|
||||
//AuthLocalDataSource will communicate with local database (hive)
|
||||
class AuthLocalDataSource {
|
||||
bool? checkIsAuth() {
|
||||
return Hive.box(authBoxKey).get(isLogInKey, defaultValue: false) ?? false;
|
||||
}
|
||||
|
||||
String? getId() {
|
||||
return Hive.box(authBoxKey).get(userIdKey, defaultValue: "0");
|
||||
}
|
||||
|
||||
Future<void> setId(String? id) async {
|
||||
Hive.box(authBoxKey).put(userIdKey, id);
|
||||
}
|
||||
|
||||
String? getName() {
|
||||
return Hive.box(authBoxKey).get(userNameKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setName(String? name) async {
|
||||
Hive.box(authBoxKey).put(userNameKey, name);
|
||||
}
|
||||
|
||||
String? getEmail() {
|
||||
return Hive.box(authBoxKey).get(userEmailKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setEmail(String? email) async {
|
||||
Hive.box(authBoxKey).put(userEmailKey, email);
|
||||
}
|
||||
|
||||
String? getMobile() {
|
||||
return Hive.box(authBoxKey).get(userMobKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setMobile(String? mobile) async {
|
||||
Hive.box(authBoxKey).put(userMobKey, mobile);
|
||||
}
|
||||
|
||||
String? getType() {
|
||||
return Hive.box(authBoxKey).get(userTypeKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setType(String? type) async {
|
||||
Hive.box(authBoxKey).put(userTypeKey, type);
|
||||
}
|
||||
|
||||
String? getProfile() {
|
||||
return Hive.box(authBoxKey).get(userProfileKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setProfile(String? image) async {
|
||||
Hive.box(authBoxKey).put(userProfileKey, image);
|
||||
}
|
||||
|
||||
String? getStatus() {
|
||||
return Hive.box(authBoxKey).get(userStatusKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setStatus(String? status) async {
|
||||
Hive.box(authBoxKey).put(userStatusKey, status);
|
||||
}
|
||||
|
||||
String getJWTtoken() {
|
||||
return Hive.box(authBoxKey).get(jwtTokenKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setJWTtoken(String? jwtToken) async {
|
||||
Hive.box(authBoxKey).put(jwtTokenKey, jwtToken);
|
||||
}
|
||||
|
||||
Future<void> changeAuthStatus(bool? authStatus) async {
|
||||
Hive.box(authBoxKey).put(isLogInKey, authStatus);
|
||||
}
|
||||
|
||||
String? getAuthorWhatsappLink() {
|
||||
return Hive.box(authBoxKey).get(authorWhatsappLinkKey, defaultValue: "");
|
||||
}
|
||||
|
||||
String? getAuthorFacebookLink() {
|
||||
return Hive.box(authBoxKey).get(authorfacebookLinkKey, defaultValue: "");
|
||||
}
|
||||
|
||||
String? getAuthorTelegramLink() {
|
||||
return Hive.box(authBoxKey).get(authorTelegramLinkKey, defaultValue: "");
|
||||
}
|
||||
|
||||
String? getAuthorLinkedInLink() {
|
||||
return Hive.box(authBoxKey).get(authorLinkedInLinkKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setSocialMediaLinks(String? whatsappLink, facebookLink, telegramLink, linkedInLink) async {
|
||||
Hive.box(authBoxKey).put(authorWhatsappLinkKey, whatsappLink);
|
||||
Hive.box(authBoxKey).put(authorfacebookLinkKey, facebookLink);
|
||||
Hive.box(authBoxKey).put(authorTelegramLinkKey, telegramLink);
|
||||
Hive.box(authBoxKey).put(authorLinkedInLinkKey, linkedInLink);
|
||||
}
|
||||
|
||||
String getAuthorBio() {
|
||||
return Hive.box(authBoxKey).get(authorBioKey, defaultValue: "");
|
||||
}
|
||||
|
||||
Future<void> setAuthorBio(String? authorBio) async {
|
||||
Hive.box(authBoxKey).put(authorBioKey, authorBio);
|
||||
}
|
||||
|
||||
AuthorStatus getAuthorStatus() {
|
||||
final value = Hive.box(authBoxKey).get(authorStatusKey, defaultValue: AuthorStatus.rejected.name);
|
||||
|
||||
return AuthorStatus.values.byName(value);
|
||||
}
|
||||
|
||||
Future<void> setAuthorStatus(AuthorStatus authorStatus) async {
|
||||
Hive.box(authBoxKey).put(authorStatusKey, authorStatus.name);
|
||||
}
|
||||
}
|
||||
299
news-app/lib/data/repositories/Auth/authRemoteDataSource.dart
Normal file
299
news-app/lib/data/repositories/Auth/authRemoteDataSource.dart
Normal file
@@ -0,0 +1,299 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
import 'package:news/cubits/appLocalizationCubit.dart';
|
||||
import 'package:news/data/repositories/Settings/settingsLocalDataRepository.dart';
|
||||
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
|
||||
import 'package:news/cubits/Auth/authCubit.dart';
|
||||
import 'package:news/ui/widgets/SnackBarWidget.dart';
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class AuthRemoteDataSource {
|
||||
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
|
||||
final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ["profile", "email"]);
|
||||
final _facebookSignin = FacebookLogin();
|
||||
|
||||
Future<dynamic> loginAuth({
|
||||
required String firebaseId,
|
||||
required String name,
|
||||
required String email,
|
||||
required String type,
|
||||
required String profile,
|
||||
required String mobile,
|
||||
}) async {
|
||||
try {
|
||||
final Map<String, String> body = {FIREBASE_ID: firebaseId, NAME: name, TYPE: type, EMAIL: email};
|
||||
if (profile != "") body[PROFILE] = profile;
|
||||
if (mobile != "") body[MOBILE] = mobile;
|
||||
|
||||
var result = await Api.sendApiRequest(body: body, url: Api.getUserSignUpApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> deleteUserAcc() async {
|
||||
try {
|
||||
final result = await Api.sendApiRequest(body: {}, url: Api.userDeleteApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
//to update fcmId of user's
|
||||
Future<dynamic> updateUserData(
|
||||
{String? name, String? mobile, String? email, String? filePath, String? authorBio, String? whatsappLink, String? facebookLink, String? telegramLink, String? linkedInLink}) async {
|
||||
try {
|
||||
Map<String, dynamic> body = {};
|
||||
Map<String, dynamic> result = {};
|
||||
|
||||
if (name != null) body[NAME] = name;
|
||||
if (mobile != null) body[MOBILE] = mobile;
|
||||
if (email != null) body[EMAIL] = email;
|
||||
if (filePath != null && filePath.isNotEmpty) body[PROFILE] = await MultipartFile.fromFile(filePath);
|
||||
if (authorBio != null) body[AUTHOR_BIO] = authorBio;
|
||||
if (whatsappLink != null) body[AUTHOR_WHATSAPP_LINK] = whatsappLink;
|
||||
if (telegramLink != null) body[AUTHOR_TELEGRAM_LINK] = telegramLink;
|
||||
if (facebookLink != null) body[AUTHOR_FACEBOOK_LINK] = facebookLink;
|
||||
if (linkedInLink != null) body[AUTHOR_LINKEDIN_LINK] = linkedInLink;
|
||||
result = await Api.sendApiRequest(body: body, url: Api.setUpdateProfileApi);
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> registerToken({required String fcmId, required BuildContext context}) async {
|
||||
try {
|
||||
final body = {TOKEN: fcmId, LANGUAGE_ID: context.read<AppLocalizationCubit>().state.id}; //Pass languageId for specific language Notifications
|
||||
|
||||
String latitude = SettingsLocalDataRepository().getLocationCityValues().first;
|
||||
String longitude = SettingsLocalDataRepository().getLocationCityValues().last;
|
||||
|
||||
if (latitude != '' && latitude != "null") body[LATITUDE] = latitude;
|
||||
if (longitude != '' && longitude != "null") body[LONGITUDE] = longitude;
|
||||
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.setRegisterToken);
|
||||
return result;
|
||||
} on SocketException catch (e) {
|
||||
throw SocketException(e.toString());
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> socialSignInUser({required AuthProviders authProvider, required BuildContext context, String? email, String? password, String? otp, String? verifiedId}) async {
|
||||
Map<String, dynamic> result = {};
|
||||
|
||||
try {
|
||||
switch (authProvider) {
|
||||
case AuthProviders.gmail:
|
||||
UserCredential? userCredential = await signInWithGoogle(context);
|
||||
if (userCredential != null) {
|
||||
result['user'] = userCredential.user!;
|
||||
return result;
|
||||
} else {
|
||||
throw ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'somethingMSg'));
|
||||
}
|
||||
|
||||
case AuthProviders.mobile:
|
||||
UserCredential? userCredential = await signInWithPhone(context: context, otp: otp!, verifiedId: verifiedId!);
|
||||
if (userCredential != null) {
|
||||
result['user'] = userCredential.user!;
|
||||
return result;
|
||||
} else {
|
||||
throw ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'somethingMSg'));
|
||||
}
|
||||
case AuthProviders.fb:
|
||||
final faceBookAuthResult = await signInWithFacebook();
|
||||
if (faceBookAuthResult != null) {
|
||||
result['user'] = faceBookAuthResult.user!;
|
||||
return result;
|
||||
} else {
|
||||
throw ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'somethingMSg'));
|
||||
}
|
||||
case AuthProviders.apple:
|
||||
UserCredential? userCredential = await signInWithApple(context);
|
||||
if (userCredential != null) {
|
||||
result['user'] = userCredential.user!;
|
||||
return result;
|
||||
} else {
|
||||
throw ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'somethingMSg'));
|
||||
}
|
||||
case AuthProviders.email:
|
||||
final userCredential = await signInWithEmailPassword(email: email!, password: password!, context: context);
|
||||
if (userCredential != null) {
|
||||
result['user'] = userCredential.user!;
|
||||
return result;
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
} on SocketException catch (_) {
|
||||
throw ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'internetmsg'));
|
||||
} on FirebaseAuthException catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<UserCredential?> signInWithPhone({required BuildContext context, required String otp, required String verifiedId}) async {
|
||||
String code = otp.trim();
|
||||
|
||||
if (code.length == 6) {
|
||||
//As OTP is of Fixed length 6
|
||||
try {
|
||||
final PhoneAuthCredential credential = PhoneAuthProvider.credential(verificationId: verifiedId, smsCode: otp);
|
||||
final UserCredential authResult = await _firebaseAuth.signInWithCredential(credential);
|
||||
final User? user = authResult.user;
|
||||
if (user != null) {
|
||||
assert(!user.isAnonymous);
|
||||
|
||||
final User? currentUser = _firebaseAuth.currentUser;
|
||||
assert(user.uid == currentUser?.uid);
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'otpMsg'), context);
|
||||
return authResult;
|
||||
} else {
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'otpError'), context);
|
||||
return null;
|
||||
}
|
||||
} on FirebaseAuthException catch (authError) {
|
||||
if (authError.code == 'invalidVerificationCode') {
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'invalidVerificationCode'), context);
|
||||
return null;
|
||||
} else {
|
||||
showSnackBar(authError.message.toString(), context);
|
||||
return null;
|
||||
}
|
||||
} on FirebaseException catch (e) {
|
||||
showSnackBar(e.message.toString(), context);
|
||||
return null;
|
||||
} catch (e) {
|
||||
showSnackBar(e.toString(), context);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'enterOtpTxt'), context);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//sign in with email and password in firebase
|
||||
Future<UserCredential?> signInWithEmailPassword({required String email, required String password, required BuildContext context}) async {
|
||||
try {
|
||||
final UserCredential userCredential = await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
|
||||
|
||||
return userCredential;
|
||||
} on FirebaseAuthException catch (authError) {
|
||||
if (authError.code == 'userNotFound') {
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'userNotFound'), context);
|
||||
} else if (authError.code == 'wrongPassword') {
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'wrongPassword'), context);
|
||||
} else {
|
||||
throw ApiMessageAndCodeException(errorMessage: authError.message!);
|
||||
}
|
||||
} on FirebaseException catch (e) {
|
||||
showSnackBar(e.toString(), context);
|
||||
} catch (e) {
|
||||
String errorMessage = e.toString();
|
||||
showSnackBar(errorMessage, context);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//signIn using google account
|
||||
Future<UserCredential?> signInWithGoogle(BuildContext context) async {
|
||||
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
|
||||
if (googleUser == null) {
|
||||
ApiMessageAndCodeException(errorMessage: UiUtils.getTranslatedLabel(context, 'somethingMSg'));
|
||||
return null;
|
||||
}
|
||||
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
|
||||
|
||||
final AuthCredential credential = GoogleAuthProvider.credential(accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
|
||||
final UserCredential userCredential = await _firebaseAuth.signInWithCredential(credential);
|
||||
return userCredential;
|
||||
}
|
||||
|
||||
Future<UserCredential?> signInWithFacebook() async {
|
||||
final res = await _facebookSignin.logIn(permissions: [FacebookPermission.publicProfile, FacebookPermission.email]);
|
||||
|
||||
// Check result status
|
||||
switch (res.status) {
|
||||
case FacebookLoginStatus.success:
|
||||
// Send access token to server for validation and auth
|
||||
final FacebookAccessToken? accessToken = res.accessToken;
|
||||
AuthCredential authCredential = FacebookAuthProvider.credential(accessToken!.token);
|
||||
final UserCredential userCredential = await _firebaseAuth.signInWithCredential(authCredential);
|
||||
return userCredential;
|
||||
case FacebookLoginStatus.cancel:
|
||||
return null;
|
||||
|
||||
case FacebookLoginStatus.error:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String sha256ofString(String input) {
|
||||
final bytes = utf8.encode(input);
|
||||
final digest = sha256.convert(bytes);
|
||||
return digest.toString();
|
||||
}
|
||||
|
||||
Future<UserCredential?> signInWithApple(BuildContext context) async {
|
||||
try {
|
||||
final rawNonce = generateNonce();
|
||||
final nonce = sha256ofString(rawNonce);
|
||||
|
||||
final appleCredential = await SignInWithApple.getAppleIDCredential(scopes: [AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName], nonce: nonce);
|
||||
|
||||
final oauthCredential = OAuthProvider("apple.com").credential(idToken: appleCredential.identityToken, rawNonce: rawNonce, accessToken: appleCredential.authorizationCode);
|
||||
|
||||
final UserCredential authResult = await FirebaseAuth.instance.signInWithCredential(oauthCredential);
|
||||
|
||||
return authResult;
|
||||
} on FirebaseAuthException catch (authError) {
|
||||
showSnackBar(authError.message!, context);
|
||||
return null;
|
||||
} on FirebaseException catch (e) {
|
||||
showSnackBar(e.toString(), context);
|
||||
return null;
|
||||
} catch (e) {
|
||||
String errorMessage = e.toString();
|
||||
|
||||
if (errorMessage == "Null check operator used on a null value") {
|
||||
//if user goes back from selecting Account
|
||||
//in case of User gmail not selected & back to Login screen
|
||||
showSnackBar(UiUtils.getTranslatedLabel(context, 'cancelLogin'), context);
|
||||
return null;
|
||||
} else {
|
||||
showSnackBar(errorMessage, context);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signOut(AuthProviders? authProvider) async {
|
||||
_firebaseAuth.signOut();
|
||||
if (authProvider == AuthProviders.gmail) {
|
||||
_googleSignIn.signOut();
|
||||
} else if (authProvider == AuthProviders.fb) {
|
||||
_facebookSignin.logOut();
|
||||
} else {
|
||||
_firebaseAuth.signOut();
|
||||
}
|
||||
}
|
||||
}
|
||||
171
news-app/lib/data/repositories/Auth/authRepository.dart
Normal file
171
news-app/lib/data/repositories/Auth/authRepository.dart
Normal file
@@ -0,0 +1,171 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:news/data/models/authorModel.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/hiveBoxKeys.dart';
|
||||
import 'package:news/utils/uiUtils.dart';
|
||||
import 'package:news/cubits/Auth/authCubit.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
import 'package:news/data/repositories/Auth/authLocalDataSource.dart';
|
||||
import 'package:news/data/repositories/Auth/authRemoteDataSource.dart';
|
||||
|
||||
class AuthRepository {
|
||||
static final AuthRepository _authRepository = AuthRepository._internal();
|
||||
late AuthLocalDataSource _authLocalDataSource;
|
||||
late AuthRemoteDataSource _authRemoteDataSource;
|
||||
|
||||
factory AuthRepository() {
|
||||
_authRepository._authLocalDataSource = AuthLocalDataSource();
|
||||
_authRepository._authRemoteDataSource = AuthRemoteDataSource();
|
||||
return _authRepository;
|
||||
}
|
||||
|
||||
AuthRepository._internal();
|
||||
|
||||
AuthLocalDataSource get authLocalDataSource => _authLocalDataSource;
|
||||
|
||||
//to get auth detials stored in hive box
|
||||
getLocalAuthDetails() {
|
||||
return {
|
||||
"isLogIn": _authLocalDataSource.checkIsAuth(),
|
||||
ID: _authLocalDataSource.getId(),
|
||||
NAME: _authLocalDataSource.getName(),
|
||||
EMAIL: _authLocalDataSource.getEmail(),
|
||||
MOBILE: _authLocalDataSource.getMobile(),
|
||||
TYPE: _authLocalDataSource.getType(),
|
||||
PROFILE: _authLocalDataSource.getProfile(),
|
||||
STATUS: _authLocalDataSource.getStatus(),
|
||||
TOKEN: _authLocalDataSource.getJWTtoken(),
|
||||
AUTHOR_BIO: _authLocalDataSource.getAuthorBio(),
|
||||
AUTHOR_STATUS: _authLocalDataSource.getAuthorStatus().name,
|
||||
AUTHOR_WHATSAPP_LINK: _authLocalDataSource.getAuthorWhatsappLink(),
|
||||
AUTHOR_FACEBOOK_LINK: _authLocalDataSource.getAuthorFacebookLink(),
|
||||
AUTHOR_TELEGRAM_LINK: _authLocalDataSource.getAuthorTelegramLink(),
|
||||
AUTHOR_LINKEDIN_LINK: _authLocalDataSource.getAuthorLinkedInLink()
|
||||
};
|
||||
}
|
||||
|
||||
setLocalAuthDetails(
|
||||
{required bool authStatus,
|
||||
required String id,
|
||||
required String name,
|
||||
required String email,
|
||||
required String mobile,
|
||||
required String type,
|
||||
required String profile,
|
||||
required String status,
|
||||
required String role,
|
||||
required String jwtToken,
|
||||
required int isAuthor,
|
||||
Author? authorDetails}) {
|
||||
_authLocalDataSource.changeAuthStatus(authStatus);
|
||||
_authLocalDataSource.setId(id);
|
||||
_authLocalDataSource.setName(name);
|
||||
_authLocalDataSource.setEmail(email);
|
||||
_authLocalDataSource.setMobile(mobile);
|
||||
_authLocalDataSource.setType(type);
|
||||
_authLocalDataSource.setProfile(profile);
|
||||
_authLocalDataSource.setStatus(status);
|
||||
_authLocalDataSource.setJWTtoken(jwtToken);
|
||||
_authLocalDataSource.setAuthorStatus((authorDetails != null) ? authorDetails.status! : AuthorStatus.rejected);
|
||||
_authLocalDataSource.setAuthorBio((authorDetails != null) ? authorDetails.bio : "");
|
||||
_authLocalDataSource.setSocialMediaLinks((authorDetails != null) ? authorDetails.whatsappLink : "", (authorDetails != null) ? authorDetails.facebookLink : "",
|
||||
(authorDetails != null) ? authorDetails.telegramLink : "", (authorDetails != null) ? authorDetails.linkedinLink : "");
|
||||
}
|
||||
|
||||
//First we signin user with given provider then add user details
|
||||
Future<Map<String, dynamic>> signInUser({required BuildContext context, required AuthProviders authProvider, String? email, String? password, String? otp, String? verifiedId}) async {
|
||||
try {
|
||||
final result = await _authRemoteDataSource.socialSignInUser(context: context, authProvider: authProvider, email: email, password: password, verifiedId: verifiedId, otp: otp);
|
||||
final user = result['user'] as User;
|
||||
var providerData = user.providerData[0];
|
||||
if (authProvider == AuthProviders.email && !user.emailVerified) {
|
||||
throw ApiException(UiUtils.getTranslatedLabel(context, 'verifyEmailMsg'));
|
||||
}
|
||||
|
||||
Map<String, dynamic> userDataTest = await _authRemoteDataSource.loginAuth(
|
||||
mobile: providerData.phoneNumber ?? "",
|
||||
email: providerData.email ?? "",
|
||||
firebaseId: user.uid,
|
||||
name: providerData.displayName ?? "",
|
||||
profile: providerData.photoURL ?? "",
|
||||
type: authProvider.name);
|
||||
if (!userDataTest[ERROR]) {
|
||||
if (userDataTest[DATA][STATUS].toString() != "0") {
|
||||
setLocalAuthDetails(
|
||||
type: userDataTest[DATA][TYPE] ?? "",
|
||||
profile: userDataTest[DATA][PROFILE] ?? "",
|
||||
name: userDataTest[DATA][NAME] ?? "",
|
||||
email: userDataTest[DATA][EMAIL] ?? "",
|
||||
authStatus: true,
|
||||
id: (userDataTest[DATA][ID].toString() != "") ? userDataTest[DATA][ID].toString() : "0",
|
||||
mobile: userDataTest[DATA][MOBILE] ?? "",
|
||||
role: userDataTest[DATA][ROLE].toString(),
|
||||
status: userDataTest[DATA][STATUS].toString(),
|
||||
jwtToken: userDataTest[DATA][TOKEN] ?? "",
|
||||
isAuthor: userDataTest[DATA][IS_AUTHOR] ?? 0,
|
||||
authorDetails: (userDataTest[DATA][IS_AUTHOR] == 1 && userDataTest[DATA][AUTHOR] != null) ? Author.fromJson(userDataTest[DATA][AUTHOR]) : null);
|
||||
}
|
||||
return userDataTest;
|
||||
} else {
|
||||
signOut(authProvider);
|
||||
throw ApiMessageAndCodeException(errorMessage: userDataTest[MESSAGE]);
|
||||
}
|
||||
} catch (e) {
|
||||
signOut(authProvider);
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> updateUserData(
|
||||
{String? name, String? mobile, String? email, String? filePath, String? authorBio, String? whatsappLink, String? facebookLink, String? telegramLink, String? linkedInLink}) async {
|
||||
final result = await _authRemoteDataSource.updateUserData(
|
||||
email: email,
|
||||
name: name,
|
||||
mobile: mobile,
|
||||
filePath: filePath,
|
||||
authorBio: authorBio,
|
||||
whatsappLink: whatsappLink,
|
||||
facebookLink: facebookLink,
|
||||
telegramLink: telegramLink,
|
||||
linkedInLink: linkedInLink);
|
||||
if (name != null) _authLocalDataSource.setName(name);
|
||||
if (mobile != null) _authLocalDataSource.setMobile(mobile);
|
||||
if (email != null) _authLocalDataSource.setEmail(email);
|
||||
if (filePath != null && filePath.isNotEmpty) _authLocalDataSource.setProfile(result[PROFILE]);
|
||||
if (authorBio != null) _authLocalDataSource.setAuthorBio(authorBio);
|
||||
if (whatsappLink != null || facebookLink != null || telegramLink != null || linkedInLink != null) _authLocalDataSource.setSocialMediaLinks(whatsappLink, facebookLink, telegramLink, linkedInLink);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> registerToken({required String fcmId, required BuildContext context}) async {
|
||||
final result = await _authRemoteDataSource.registerToken(fcmId: fcmId, context: context);
|
||||
return result;
|
||||
}
|
||||
|
||||
//to delete my account
|
||||
Future<dynamic> deleteUser() async {
|
||||
final result = await _authRemoteDataSource.deleteUserAcc();
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> signOut(AuthProviders authProvider) async {
|
||||
_authRemoteDataSource.signOut(authProvider);
|
||||
await _authLocalDataSource.changeAuthStatus(false);
|
||||
await _authLocalDataSource.setId("0");
|
||||
await _authLocalDataSource.setName("");
|
||||
await _authLocalDataSource.setEmail("");
|
||||
await _authLocalDataSource.setMobile("");
|
||||
await _authLocalDataSource.setType("");
|
||||
await _authLocalDataSource.setProfile("");
|
||||
await _authLocalDataSource.setStatus("");
|
||||
await _authLocalDataSource.setJWTtoken("");
|
||||
await _authLocalDataSource.setAuthorBio("");
|
||||
await _authLocalDataSource.setAuthorStatus(AuthorStatus.rejected);
|
||||
await _authLocalDataSource.setSocialMediaLinks("", "", "", "");
|
||||
await Hive.box(authBoxKey).clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
class BookmarkRemoteDataSource {
|
||||
Future<dynamic> getBookmark({required String langId, required String offset, required String perPage}) async {
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId, OFFSET: offset, LIMIT: perPage};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getBookmarkApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future addBookmark({required String newsId, required String status}) async {
|
||||
try {
|
||||
final body = {NEWS_ID: newsId, STATUS: status};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.setBookmarkApi);
|
||||
return result[DATA];
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'package:news/data/models/NewsModel.dart';
|
||||
import 'package:news/data/repositories/Bookmark/bookmarkRemoteDataSource.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class BookmarkRepository {
|
||||
static final BookmarkRepository _bookmarkRepository = BookmarkRepository._internal();
|
||||
late BookmarkRemoteDataSource _bookmarkRemoteDataSource;
|
||||
|
||||
factory BookmarkRepository() {
|
||||
_bookmarkRepository._bookmarkRemoteDataSource = BookmarkRemoteDataSource();
|
||||
return _bookmarkRepository;
|
||||
}
|
||||
|
||||
BookmarkRepository._internal();
|
||||
|
||||
Future<Map<String, dynamic>> getBookmark({required String offset, required String limit, required String langId}) async {
|
||||
final result = await _bookmarkRemoteDataSource.getBookmark(perPage: limit, offset: offset, langId: langId);
|
||||
return (result[ERROR])
|
||||
? {ERROR: result[ERROR], MESSAGE: result[MESSAGE]}
|
||||
: {ERROR: result[ERROR], "total": result[TOTAL], "Bookmark": (result[DATA] as List).map((e) => NewsModel.fromJson(e)).toList()};
|
||||
}
|
||||
|
||||
Future setBookmark({required String newsId, required String status}) async {
|
||||
final result = await _bookmarkRemoteDataSource.addBookmark(status: status, newsId: newsId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class BreakingNewsRemoteDataSource {
|
||||
Future<dynamic> getBreakingNews({required String langId}) async {
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getBreakingNewsApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'package:news/data/models/BreakingNewsModel.dart';
|
||||
import 'package:news/data/repositories/BreakingNews/breakNewsRemoteDataSource.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class BreakingNewsRepository {
|
||||
static final BreakingNewsRepository _breakingNewsRepository = BreakingNewsRepository._internal();
|
||||
|
||||
late BreakingNewsRemoteDataSource _breakingNewsRemoteDataSource;
|
||||
|
||||
factory BreakingNewsRepository() {
|
||||
_breakingNewsRepository._breakingNewsRemoteDataSource = BreakingNewsRemoteDataSource();
|
||||
return _breakingNewsRepository;
|
||||
}
|
||||
|
||||
BreakingNewsRepository._internal();
|
||||
|
||||
Future<dynamic> getBreakingNews({required String langId}) async {
|
||||
final result = await _breakingNewsRemoteDataSource.getBreakingNews(langId: langId);
|
||||
|
||||
return (result[ERROR]) ? {ERROR: result[ERROR], MESSAGE: result[MESSAGE]} : {ERROR: result[ERROR], "BreakingNews": (result[DATA] as List).map((e) => BreakingNewsModel.fromJson(e)).toList()};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CategoryRemoteDataSource {
|
||||
Future<dynamic> getCategory({required String limit, required String offset, required String langId}) async {
|
||||
try {
|
||||
final body = {LIMIT: limit, OFFSET: offset, LANGUAGE_ID: langId};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getCatApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:news/data/models/CategoryModel.dart';
|
||||
import 'package:news/data/repositories/Category/categoryRemoteDataSource.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CategoryRepository {
|
||||
static final CategoryRepository _notificationRepository = CategoryRepository._internal();
|
||||
|
||||
late CategoryRemoteDataSource _notificationRemoteDataSource;
|
||||
|
||||
factory CategoryRepository() {
|
||||
_notificationRepository._notificationRemoteDataSource = CategoryRemoteDataSource();
|
||||
return _notificationRepository;
|
||||
}
|
||||
|
||||
CategoryRepository._internal();
|
||||
|
||||
Future<Map<String, dynamic>> getCategory({required String offset, required String limit, required String langId}) async {
|
||||
final result = await _notificationRemoteDataSource.getCategory(limit: limit, offset: offset, langId: langId);
|
||||
|
||||
return (result[ERROR])
|
||||
? {ERROR: result[ERROR], MESSAGE: result[MESSAGE]}
|
||||
: {ERROR: result[ERROR], "total": result[TOTAL], "Category": (result[DATA] as List).map((e) => CategoryModel.fromJson(e)).toList()};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CommentNewsRemoteDataSource {
|
||||
Future<dynamic> getCommentNews({required String limit, required String offset, required String newsId}) async {
|
||||
try {
|
||||
final body = {LIMIT: limit, OFFSET: offset, NEWS_ID: newsId};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getCommentByNewsApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'package:news/data/models/CommentModel.dart';
|
||||
import 'package:news/data/repositories/CommentNews/commNewsRemoteDataSource.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class CommentNewsRepository {
|
||||
static final CommentNewsRepository _commentNewsRepository = CommentNewsRepository._internal();
|
||||
|
||||
late CommentNewsRemoteDataSource _commentNewsRemoteDataSource;
|
||||
|
||||
factory CommentNewsRepository() {
|
||||
_commentNewsRepository._commentNewsRemoteDataSource = CommentNewsRemoteDataSource();
|
||||
return _commentNewsRepository;
|
||||
}
|
||||
|
||||
CommentNewsRepository._internal();
|
||||
|
||||
Future<Map<String, dynamic>> getCommentNews({required String offset, required String limit, required String newsId}) async {
|
||||
final result = await _commentNewsRemoteDataSource.getCommentNews(limit: limit, offset: offset, newsId: newsId);
|
||||
if (result[ERROR]) {
|
||||
return {ERROR: result[ERROR], MESSAGE: result[MESSAGE]};
|
||||
} else {
|
||||
final List<CommentModel> commentsList = (result[DATA] as List).map((e) => CommentModel.fromJson(e)).toList();
|
||||
final List<ReplyModel> replyList = [];
|
||||
for (var i in commentsList) {
|
||||
replyList.addAll(i.replyComList as List<ReplyModel>);
|
||||
}
|
||||
return {ERROR: result[ERROR], "total": result[TOTAL], "CommentNews": commentsList};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import '../../../utils/api.dart';
|
||||
import '../../../utils/strings.dart';
|
||||
|
||||
class DeleteImageRemoteDataSource {
|
||||
Future deleteImage({required String imageId}) async {
|
||||
try {
|
||||
final body = {
|
||||
ID: imageId,
|
||||
};
|
||||
final result = await Api.sendApiRequest(
|
||||
body: body,
|
||||
url: Api.setDeleteImageApi,
|
||||
);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'deleteImageIdRemoteDataSource.dart';
|
||||
|
||||
class DeleteImageRepository {
|
||||
static final DeleteImageRepository _deleteImageRepository = DeleteImageRepository._internal();
|
||||
late DeleteImageRemoteDataSource _deleteImageRemoteDataSource;
|
||||
|
||||
factory DeleteImageRepository() {
|
||||
_deleteImageRepository._deleteImageRemoteDataSource = DeleteImageRemoteDataSource();
|
||||
return _deleteImageRepository;
|
||||
}
|
||||
|
||||
DeleteImageRepository._internal();
|
||||
|
||||
Future setDeleteImage({
|
||||
required String imageId,
|
||||
}) async {
|
||||
final result = await _deleteImageRemoteDataSource.deleteImage(imageId: imageId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class DeleteUserNewsRemoteDataSource {
|
||||
Future deleteUserNews({required String newsId}) async {
|
||||
try {
|
||||
final body = {
|
||||
ID: newsId,
|
||||
};
|
||||
final result = await Api.sendApiRequest(
|
||||
body: body,
|
||||
url: Api.setDeleteNewsApi,
|
||||
);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'deleteUserNewsRemoteDataSource.dart';
|
||||
|
||||
class DeleteUserNewsRepository {
|
||||
static final DeleteUserNewsRepository _deleteUserNewsRepository = DeleteUserNewsRepository._internal();
|
||||
late DeleteUserNewsRemoteDataSource _deleteUserNewsRemoteDataSource;
|
||||
|
||||
factory DeleteUserNewsRepository() {
|
||||
_deleteUserNewsRepository._deleteUserNewsRemoteDataSource = DeleteUserNewsRemoteDataSource();
|
||||
return _deleteUserNewsRepository;
|
||||
}
|
||||
|
||||
DeleteUserNewsRepository._internal();
|
||||
|
||||
Future setDeleteUserNews({
|
||||
required String newsId,
|
||||
}) async {
|
||||
final result = await _deleteUserNewsRemoteDataSource.deleteUserNews(newsId: newsId);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class DeleteUserNotiRemoteDataSource {
|
||||
Future deleteUserNotification({required String id}) async {
|
||||
try {
|
||||
final body = {ID: id};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.deleteUserNotiApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:news/data/repositories/DeleteUserNotification/deleteUserNotiRemoteDataSource.dart';
|
||||
|
||||
class DeleteUserNotiRepository {
|
||||
static final DeleteUserNotiRepository _deleteUserNotiRepository = DeleteUserNotiRepository._internal();
|
||||
late DeleteUserNotiRemoteDataSource _deleteUserNotiRemoteDataSource;
|
||||
|
||||
factory DeleteUserNotiRepository() {
|
||||
_deleteUserNotiRepository._deleteUserNotiRemoteDataSource = DeleteUserNotiRemoteDataSource();
|
||||
return _deleteUserNotiRepository;
|
||||
}
|
||||
|
||||
DeleteUserNotiRepository._internal();
|
||||
|
||||
Future deleteUserNotification({required String id}) async {
|
||||
final result = await _deleteUserNotiRemoteDataSource.deleteUserNotification(id: id);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:news/utils/api.dart';
|
||||
import 'package:news/utils/constant.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class SectionRemoteDataSource {
|
||||
Future<dynamic> getSections({required String langId, String? latitude, String? longitude, String? limit, String? offset, String? sectionOffset}) async {
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId, LIMIT: limit, OFFSET: offset, SECTION_LIMIT: limitOfSectionsData, SECTION_OFFSET: sectionOffset};
|
||||
|
||||
if (latitude != null && latitude != "null") body[LATITUDE] = latitude;
|
||||
if (longitude != null && longitude != "null") body[LONGITUDE] = longitude;
|
||||
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getFeatureSectionApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:news/data/models/FeatureSectionModel.dart';
|
||||
import 'package:news/data/repositories/FeatureSection/sectionRemoteDataSource.dart';
|
||||
import 'package:news/utils/strings.dart';
|
||||
|
||||
class SectionRepository {
|
||||
static final SectionRepository _sectionRepository = SectionRepository._internal();
|
||||
|
||||
late SectionRemoteDataSource _sectionRemoteDataSource;
|
||||
|
||||
factory SectionRepository() {
|
||||
_sectionRepository._sectionRemoteDataSource = SectionRemoteDataSource();
|
||||
return _sectionRepository;
|
||||
}
|
||||
|
||||
SectionRepository._internal();
|
||||
|
||||
Future<Map<String, dynamic>> getSection({required String langId, String? latitude, String? longitude, String? limit, String? offset, String? sectionOffset}) async {
|
||||
final result = await _sectionRemoteDataSource.getSections(langId: langId, latitude: latitude, longitude: longitude, limit: limit, offset: offset, sectionOffset: sectionOffset);
|
||||
|
||||
return (result[ERROR])
|
||||
? {ERROR: result[ERROR], MESSAGE: result[MESSAGE]}
|
||||
: {ERROR: result[ERROR], "Section": (result[DATA] as List).map((e) => FeatureSectionModel.fromJson(e)).toList(), TOTAL: result[TOTAL]};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:news/utils/strings.dart';
|
||||
import 'package:news/utils/api.dart';
|
||||
|
||||
class GetSurveyAnsRemoteDataSource {
|
||||
Future<dynamic> getSurveyAns({required String langId}) async {
|
||||
try {
|
||||
final body = {LANGUAGE_ID: langId};
|
||||
final result = await Api.sendApiRequest(body: body, url: Api.getQueResultApi);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw ApiMessageAndCodeException(errorMessage: e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user