Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
16 kB
2
Indexable
Never
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:mighty_sort_news/utils/AppImages.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:page_transition/page_transition.dart';

import '../main.dart';
import '../models/AdsModel.dart';
import '../models/NewsData.dart';
import '../screens/user/HomeFragment.dart';
import '../screens/user/WebViewScreen.dart';
import '../screens/user/components/ChewieDemo.dart';
import '../screens/user/components/YoutubeComponent.dart';
import '../utils/Colors.dart';
import '../utils/Common.dart';
import '../utils/Constants.dart';
import '../utils/ModelKeys.dart';
import 'AdMobAdComponent.dart';
import 'AppWidgets.dart';
import 'FacebookAdComponent.dart';

class FeedComponent extends StatefulWidget {
  final NewsData? data;
  final int? id;
  final bool? isNotification;

  FeedComponent({this.data, this.id, this.isNotification = false});

  @override
  _FeedComponentState createState() => _FeedComponentState();
}

class _FeedComponentState extends State<FeedComponent> {
  PageController pageController = PageController();
  AdMobAdsModel bannerAdsModel = AdMobAdsModel();
  int? currentInd = 0;

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    // youTubeInitialization();
    if (getBoolAsync(DISABLE_AD) == false) {
      if (getStringAsync(AD_TYPE) == Admob) {
        loadBannerAds();
      } else {
        loadFacebookBannerId();
      }
    }
    newsService.newsDetail(widget.data!.id).then((value) {
      if (!postViewedList.contains(widget.data!.id)) {
        newsService.updatePostCount(widget.data!.id);
        postViewedList.add(widget.data!.id);
        setValue(POST_VIEWED_LIST, jsonEncode(postViewedList));
      }
    }).catchError((e) {
      toast(e.toString());
    });
  }

  void fullScreen() {
    if (MediaQuery.of(context).orientation == DeviceOrientation.portraitUp) {
      SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
    }
  }

  Future<void> loadBannerAds() {
    return adsService.getAdMobAds().then((value) {
      bannerAdsModel = value;
    });
  }

  @override
  void dispose() {
    if (widget.data!.imageType == FULL_SCREEN_IMAGE) pageController.dispose();
    super.dispose();
  }

  @override
  void setState(fn) {
    if (mounted) super.setState(fn);
  }

  Future<void> bookmarkNews(NewsData data) async {
    if (appStore.isLoggedIn) {
      if (bookmarkList.contains(data.id)) {
        removeToBookmark(data);
      } else {
        addToBookmark(data);
      }

      toast(languages.save);
      setState(() {});
    }
  }

  Future<void> addToBookmark(NewsData data) async {
    bookmarkList.add(data.id);
    await setValue(BOOKMARKS, jsonEncode(bookmarkList));

    await userService.updateDocument({UserKeys.bookmarks: bookmarkList}, appStore.userId);
  }

  Future<void> removeToBookmark(NewsData data) async {
    bookmarkList.remove(data.id);
    await setValue(BOOKMARKS, jsonEncode(bookmarkList));

    await userService.updateDocument({UserKeys.bookmarks: bookmarkList}, appStore.userId);
  }

  Widget imageComponent() {
    if (widget.data!.imageType == BANNER_IMAGES)
      return cachedImage(widget.data!.image, width: context.width(), height: context.height() * 0.4, fit: BoxFit.cover);
    else if (widget.data!.imageType == FULL_SCREEN_IMAGE) {
      if (widget.data!.imageArray != null && widget.data!.imageArray!.isNotEmpty)
        return SizedBox(
          height: context.height(),
          child: PageView.builder(
            controller: pageController,
            itemCount: widget.data!.imageArray!.length,
            itemBuilder: (BuildContext context, int itemIndex) {
              return Stack(
                children: [
                  widget.data!.imageArray![itemIndex].isEmptyOrNull
                      ? Image.asset(ic_placeholder, width: context.width(), height: context.height(), fit: BoxFit.cover)
                      : cachedImage(widget.data!.imageArray![itemIndex], width: context.width(), height: context.height(), fit: BoxFit.cover),
                  if (itemIndex == 0)
                    Container(
                      decoration: boxDecorationWithRoundedCorners(
                        gradient: LinearGradient(
                          colors: [Colors.black45, Colors.black45],
                        ),
                      ),
                      width: context.width(),
                      height: context.height(),
                    ),
                ],
              );
            },
            onPageChanged: (v) {
              currentInd = v;
              setState(() {});
              if (v == widget.data!.imageArray!.length + 1) Navigator.push(context, PageTransition(type: PageTransitionType.leftToRight, child: HomeFragment()));
            },
          ),
        );
      else
        return Stack(
          children: [
            Image.asset(ic_placeholder, width: context.width(), height: context.height(), fit: BoxFit.cover).cornerRadiusWithClipRRect(10),
            Container(
              width: context.width(),
              height: context.height(),
              decoration: boxDecorationWithRoundedCorners(
                gradient: LinearGradient(
                  colors: [Colors.black45, Colors.black45],
                ),
              ),
            ),
          ],
        );
    } else if (widget.data!.imageType == YOUTUBE_URL)
      return YouTubeComponent(image: widget.data!.image.validate());
    else if (widget.data!.imageType == MP4_VIDEO || widget.data!.imageType == FULL_MP4_VIDEO)
      return ChewieDemo(widget.data!.image.validate(), ic_logo, widget.data!.imageType);
    else
      return Image.asset(ic_logo, width: context.width(), height: context.height() * 0.4, fit: BoxFit.cover);
  }

  @override
  Widget build(BuildContext context) {
    return widget.data!.imageType == FULL_MP4_VIDEO
        ? imageComponent()
        : widget.data!.imageType == FULL_SCREEN_IMAGE
            ? Column(
                children: [
                  Stack(
                    clipBehavior: Clip.none,
                    alignment: Alignment.center,
                    children: [
                      imageComponent(),
                      if (currentInd == 0)
                        Positioned(
                          top: context.statusBarHeight + 40,
                          left: 16,
                          right: 16,
                          child: Column(
                            children: [
                              Text(parseHtmlString(widget.data!.title.validate()),
                                      style: boldTextStyle(size: !getDeviceTypePhone() ? 26 : 20, color: Colors.white), textAlign: TextAlign.center, maxLines: 4)
                                  .center(),
                              8.height,
                              // Row(
                              //   children: [
                              //     Icon(Icons.access_time, size: 16, color: Colors.white),
                              //     4.width,
                              //     if (widget.data!.createdAt != null) Text(widget.data!.createdAt!.timeAgo, style: secondaryTextStyle(size: !getDeviceTypePhone() ? 16 : 14, color: Colors.white)),
                              //     4.width,
                              //     Text('・', style: secondaryTextStyle()),
                              //     4.width,
                              //     Text('${(parseHtmlString(widget.data!.shortContent).calculateReadTime()).ceilToDouble().toInt()} ${languages.minRead}',
                              //         style: secondaryTextStyle(size: 12, color: Colors.white)),
                              //   ],
                              // ),
                              Text(widget.data!.shortContent.validate(), style: primaryTextStyle(color: Colors.white), textAlign: TextAlign.start),

                              8.height,
                              // if (!widget.data!.content.isEmptyOrNull) HtmlWidget(postContent: widget.data!.content.validate(), color: Colors.white),
                            ],
                          ),
                        ),
                      Positioned(bottom: 150, right: 0, left: 0, child: DotIndicator(pageController: pageController, pages: widget.data!.imageArray!)),
                      Positioned(
                        bottom: 0,
                        left: 0,
                        right: 0,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // Text(languages.readMore, style: boldTextStyle(color: Colors.white)).onTap(() {
                            //   NewsDetailScreen(id: widget.data!.id).launch(context);
                            // }).paddingLeft(16),
                            if (!widget.data!.sourceUrl.isEmptyOrNull)
                              Text('Swipe left for more at ${getDomainNameFromUrl(widget.data!.sourceUrl.validate())} ', style: secondaryTextStyle(color: Colors.white)).paddingLeft(16).onTap(() {
                                WebViewScreen(mInitialUrl: widget.data!.sourceUrl, name: widget.data!.title).launch(context);
                              }),

                            Align(
                              alignment: Alignment.bottomCenter,
                              child: Column(
                                children: [
                                  Icon(MaterialIcons.keyboard_arrow_up, size: 22, color: Colors.white.withOpacity(0.7)),
                                  Text(languages.swipeUp, style: secondaryTextStyle(size: 14, color: Colors.white.withOpacity(0.7))),
                                ],
                              ),
                            ),
                            if (getBoolAsync(DISABLE_AD) == true) 16.height,
                            getBoolAsync(DISABLE_AD) == false
                                ? getStringAsync(AD_TYPE) == Admob
                                    ? Container(child: AdWidget(ad: buildBannerAd()..load()), height: buildBannerAd().size.height.toDouble())
                                    : loadFacebookBannerId()
                                : SizedBox(),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              )
            : Column(
                children: [
                  Stack(
                    clipBehavior: Clip.none,
                    alignment: Alignment.bottomLeft,
                    children: [
                      imageComponent(),
                      Positioned(
                        bottom: -10,
                        left: 16,
                        child: Container(
                          padding: EdgeInsets.all(4),
                          decoration: boxDecorationWithRoundedCorners(backgroundColor: colorPrimary.withOpacity(0.5)),
                          child: Text(appName, style: boldTextStyle(color: white)),
                        ),
                      )
                    ],
                  ),
                  16.height,
                  SizedBox(
                    height: getBoolAsync(DISABLE_AD) == false
                        ? getDeviceTypePhone()
                            ? context.height() * 0.57
                            : context.height() * 0.58
                        : getDeviceTypePhone()
                            ? context.height() * 0.55
                            : context.height() * 0.5,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(parseHtmlString(widget.data!.title.validate()), style: boldTextStyle(size: !getDeviceTypePhone() ? 26 : 20, color: textPrimaryColorGlobal), maxLines: 4),
                                8.height,
                                // Row(
                                //   children: [
                                //     Icon(Icons.access_time, size: 16, color: textSecondaryColorGlobal),
                                //     4.width,
                                //     if (widget.data!.createdAt != null) Text(widget.data!.createdAt!.timeAgo, style: secondaryTextStyle(size: !getDeviceTypePhone() ? 16 : 14)),
                                //     4.width,
                                //     Text('・', style: secondaryTextStyle()),
                                //     4.width,
                                //     Text('${(parseHtmlString(widget.data!.shortContent).calculateReadTime()).ceilToDouble().toInt()} ${languages.minRead}', style: secondaryTextStyle(size: 12)),
                                //   ],
                                // ),
                                if (!widget.data!.sourceUrl.isEmptyOrNull) Text(widget.data!.shortContent.validate(), style: primaryTextStyle()),

                                8.height,
                              ],
                            ).paddingSymmetric(horizontal: 16),
                            // if (!widget.data!.content.isEmptyOrNull) HtmlWidget(postContent: widget.data!.content.validate()).paddingSymmetric(horizontal: 12).expand(),
                          ],
                        ).expand(),
                        if (!widget.data!.sourceUrl.isEmptyOrNull)
                          Text('Swipe left for more at ${getDomainNameFromUrl(widget.data!.sourceUrl.validate())} ', style: secondaryTextStyle()).paddingLeft(16).onTap(() {
                            WebViewScreen(mInitialUrl: widget.data!.sourceUrl, name: widget.data!.title).launch(context);
                          }),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Column(
                            children: [
                              Icon(MaterialIcons.keyboard_arrow_up, size: 22, color: textSecondaryColorGlobal.withOpacity(0.7)),
                              Text(languages.swipeUp, style: secondaryTextStyle(size: 14, color: textSecondaryColorGlobal.withOpacity(0.7))),
                            ],
                          ),
                        ),
                        if (getBoolAsync(DISABLE_AD) == true) 16.height,
                        getBoolAsync(DISABLE_AD) == false
                            ? getStringAsync(AD_TYPE) == Admob
                                ? Container(child: AdWidget(ad: buildBannerAd()..load()), height: buildBannerAd().size.height.toDouble())
                                : loadFacebookBannerId()
                            : SizedBox(),
                      ],
                    ),
                  ),
                ],
              );
  }
}
Leave a Comment