feed

mail@pastecode.io avatar
unknown
dart
2 years ago
58 kB
2
Indexable
Never
import 'package:carousel_slider/carousel_slider.dart';
import 'package:chewie/chewie.dart';
import 'package:dio/dio.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:mobile/app/Dto/like_dto.dart';
import 'package:mobile/app/Dto/provider_follow_dto.dart';
import 'package:mobile/app/Utilities/methods.dart';
import 'package:mobile/app/global_widgets/favorite_button.dart';
import 'package:mobile/app/models/new/app_user_model.dart';
import 'package:mobile/app/models/responses/get_all_posts_response.dart';
import 'package:mobile/app/models/responses/get_all_provier_following.dart';
import 'package:mobile/app/models/responses/provider_followers_response.dart';
import 'package:mobile/app/modules/account/controllers/account_controller.dart';
import 'package:mobile/app/modules/chat/views/Chats.dart';
import 'package:mobile/app/modules/feed/controller/comments_controller.dart';
// import 'package:mobile/app/modules/account/views/posts_view.dart';
import 'package:mobile/app/modules/feed/controller/feed_controller.dart';
import 'package:mobile/app/modules/feed/controller/likes_controller.dart';
import 'package:mobile/app/modules/feed/view/widgets/feed_comments_list.dart';
import 'package:mobile/app/modules/feed/view/widgets/feed_likes_list.dart';
import 'package:mobile/app/modules/root/controllers/root_controller.dart';
import 'package:mobile/app/other_provider_account/controller/other_provider_controller.dart';
import 'package:mobile/app/other_provider_account/views/another_provider_account_view.dart';
import 'package:mobile/app/providers/api_provider.dart';
import 'package:mobile/app/routes/app_pages.dart';
import 'package:mobile/app/services/auth_service.dart';
import 'package:readmore/readmore.dart';
import 'package:video_player/video_player.dart';
import 'package:mobile/common/ui.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:volume_watcher/volume_watcher.dart';
// import 'package:mobile/app/modules/feed/controller/feed_controller.dart';

class FeedView extends GetView<FeedController> {
  final FeedController feedController = Get.put(FeedController());
  final FeedLikesController feedLikesController =
      Get.put(FeedLikesController());

  final FeedCommentsController feedcommentsController =
      Get.put(FeedCommentsController());

  AppUser _currentUser = Get.find<AuthService>().appUser.value;

  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: false,
      body: RefreshIndicator(
        color: Get.theme.focusColor,
        onRefresh: () async {
          await controller.refreshPage(1);
        },
        child: Obx(
          () => controller.feed.length <= 0
              ? Center(
                  child: CircularProgressIndicator(
                    color: Get.theme.focusColor,
                  ),
                )
              : Padding(
                  padding: EdgeInsets.only(top: 25),
                  child: Column(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          color: Get.theme.primaryColor,
                          // margin: EdgeInsets.only(left: 8, right: 8, top: 35),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              IconButton(
                                onPressed: () =>
                                    {Scaffold.of(context).openDrawer()},
                                icon: SvgPicture.asset(
                                    'assets/svg/menu_icon_black.svg'),
                              ),
                              Text(
                                "Posts".tr,
                                style: Get.theme.textTheme.headline5
                                    .merge(
                                      TextStyle(
                                          color: context.theme.hoverColor,
                                          fontWeight: FontWeight.w600),
                                    )
                                    .copyWith(fontSize: 21.0),
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  IconButton(
                                    icon: _currentUser.id != null
                                        ? SvgPicture.asset(
                                            'assets/svg/Icon-notifications.svg')
                                        : Icon(
                                            Icons.notifications_active,
                                          ),
                                    onPressed: () =>
                                        Get.toNamed(Routes.NOTIFICATIONS),
                                  ),
                                  IconButton(
                                    icon: Icon(
                                      Icons.search,
                                      color: Colors.black,
                                    ),
                                    onPressed: () =>
                                        Get.toNamed(Routes.FEED_SEARCH),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 9,
                        child: Container(
                          decoration: BoxDecoration(),
                          child: NotificationListener<ScrollNotification>(
                            onNotification: (ScrollNotification scrollInfo) {
                              if (!controller.isLoading.value &&
                                  scrollInfo.metrics.pixels ==
                                      scrollInfo.metrics.maxScrollExtent) {
                                controller.isLoading.value = true;
                                controller.incrementPage();
                                controller.getAllPosts(controller.pageIndex.value);

                                return true;
                              }
                              return false;
                            },
                            child: ListView.builder(
                                padding: EdgeInsets.zero,
                                itemCount: controller.feed
                                    .where((element) => element.url != null)
                                    .toList()
                                    .length,
                                itemBuilder: (context, indexPath) {
                                  return listItem(
                                      controller.feed
                                          .where((element) => element.url != null)
                                          .toList()[indexPath],
                                      context);
                                },
                              ),
                             ),
                        ),
                      ),
                      Container(
                        height: controller.isLoading.value ? 50.0 : 0,
                        child: Center(
                          child: new CircularProgressIndicator(
                            color: Get.theme.accentColor,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
        ),
      ),
    );
  }

  Widget listItem(PostsItems e, BuildContext context) {
    return FeedItem(
      e: e,
      currentUser: _currentUser,
      feedLikesController: feedLikesController,
      feedController: feedController,
      feedcommentsController: feedcommentsController,
      rootController: Get.put(RootController()),
      accountController: Get.put(AccountController()),
    );
  }
}

class FeedItem extends StatelessWidget {
  const FeedItem(
      {Key key,
      @required AppUser currentUser,
      @required this.feedController,
      @required this.feedLikesController,
      @required this.feedcommentsController,
      @required this.rootController,
      @required this.e,
      this.accountController,})
      : _currentUser = currentUser,
        super(key: key);

  final PostsItems e;
  final FeedController feedController;
  final FeedLikesController feedLikesController;
  final FeedCommentsController feedcommentsController;
  final RootController rootController;
  final AccountController accountController;

  final AppUser _currentUser;

  @override
  Widget build(BuildContext context) {
    dynamic like = e.isLiked;
    return e.url.isNotEmpty
        ? Container(
            color: Get.theme.primaryColor,
            width: Get.width,
            child: Column(
              children: [
                Column(
                  children: [
                    Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    InkWell(
                                      onTap: () async {
                                        if (e.providerId != _currentUser.id) {
                                          Get.dialog(
                                            Center(
                                              child: CircularProgressIndicator(
                                                valueColor:
                                                    AlwaysStoppedAnimation<
                                                        Color>(
                                                  Get.theme.accentColor,
                                                ),
                                              ),
                                            ),
                                            barrierDismissible: true,
                                          );
                                          final OtherProviderController
                                              otherProviderController = Get.find();
                                        
                                          await otherProviderController
                                              .getAllProviderData(e.providerId);
                                          Get.to(AnotherProvider())
                                              .then((value) => Get.back());
                                        } else {
                                          rootController.changePageInRoot(3);
                                        }
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(
                                            top: 10.0, bottom: 5.0),
                                        padding: EdgeInsets.all(5.0),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: <Widget>[
                                            Stack(
                                              children: [
                                                e.providerProfileUrl != null
                                                    ? ClipRRect(
                                                        borderRadius:
                                                            new BorderRadius
                                                                .circular(50.0),
                                                        child: CircleAvatar(
                                                          backgroundColor:
                                                              Ui.parseColor(
                                                                  "#BEBEBE"),
                                                          radius: 22,
                                                          child:
                                                              FancyShimmerImage(
                                                            imageUrl: e
                                                                .providerProfileUrl,
                                                            width: 60,
                                                            height: 60,
                                                          ),
                                                          backgroundImage:
                                                              NetworkImage(
                                                            '${e.providerProfileUrl}',
                                                          ),
                                                        ),
                                                      )
                                                    : ClipRRect(
                                                        borderRadius:
                                                            new BorderRadius
                                                                .circular(50.0),
                                                        child: Image.asset(
                                                          'assets/img/def_user.jpg',
                                                          width: 60,
                                                          height: 60,
                                                        ),
                                                      ),
                                                Positioned(
                                                  top: e.providerProfileUrl ==
                                                          null
                                                      ? 8
                                                      : 0,
                                                  right: e.providerProfileUrl ==
                                                          null
                                                      ? 8
                                                      : 0,
                                                  child: InkWell(
                                                    onTap: () {},
                                                    child: e.isLicenseActive ==
                                                            true
                                                        ? CircleAvatar(
                                                            backgroundColor: Get
                                                                .theme
                                                                .focusColor,
                                                            radius: 8,
                                                            child: Icon(
                                                              Icons.check,
                                                              size: 12,
                                                              color: Get.theme
                                                                  .primaryColor,
                                                            ),
                                                          )
                                                        : SizedBox(),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            SizedBox(
                                              width: 5.0,
                                            ),
                                            Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              mainAxisSize: MainAxisSize.min,
                                              children: <Widget>[
                                                Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Text(
                                                      e.providerName,
                                                      textScaleFactor: 1.0,
                                                      style: TextStyle(
                                                        color: Colors.black,
                                                        fontSize: 14.0,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ).marginOnly(top: 8, bottom: 8),
                                                Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: <Widget>[
                                                      Icon(
                                                        Icons.access_time,
                                                        color: Colors.black
                                                            .withOpacity(0.7),
                                                        size: 15.0,
                                                      ),
                                                      SizedBox(
                                                        width: 5.0,
                                                      ),
                                                      Text(
                                                        AppMethodsAndUtilities()
                                                            .getVerboseDateTimeRepresentation(
                                                                e.createdDate),
                                                        style: TextStyle(
                                                            color: Colors.black
                                                                .withOpacity(
                                                                    0.7),
                                                            fontSize: 13),
                                                      ),
                                                    ])
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    e.providerId != _currentUser.id
                                        ? Obx(
                                            () => accountController
                                                    .following.value
                                                    .where((element) =>
                                                        element.providerId ==
                                                        e.providerId)
                                                    .isEmpty
                                                ? TextButton(
                                                    child: Text(
                                                      "Follow".tr,
                                                      style: Get
                                                          .textTheme.bodyText1
                                                          .copyWith(
                                                              color: Get.theme
                                                                  .focusColor,
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w600),
                                                    ),
                                                    onPressed: () async {
                                                      ProviderFollowDto param =
                                                          ProviderFollowDto(
                                                        providerId:
                                                            e.providerId,
                                                        requesterId:
                                                            _currentUser.id,
                                                        isfollow: true,
                                                      );

                                                      Get.log(
                                                          "trying to add follower");
                                                      await ApiProvider(
                                                              httpClient: Dio())
                                                          .addOtherProviderFollow(
                                                              param)
                                                          .then((value) {
                                                        accountController
                                                            .following
                                                            .add(
                                                          providerFollowingItems(
                                                            isfollow: true,
                                                            requesterId:
                                                                e.providerId,
                                                            providerId:
                                                                _currentUser.id,
                                                            providerName:
                                                                e.providerName,
                                                            requesterName:
                                                                _currentUser
                                                                    .name,
                                                            providerUrl: e
                                                                .providerProfileUrl,
                                                            requesterUrl:
                                                                _currentUser
                                                                    .profilePictureUrl,
                                                            createdDate:
                                                                DateTime.now()
                                                                    .toString(),
                                                            id: value,
                                                          ),
                                                        );
                                                        accountController
                                                            .getAllFollowing();
                                                      });
                                                    },
                                                  )
                                                : TextButton(
                                                    child: Text(
                                                      "Following".tr,
                                                      style: Get
                                                          .textTheme.bodyText1
                                                          .copyWith(
                                                              color:
                                                                  Ui.parseColor(
                                                                      "#262626 "),
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w600),
                                                    ),
                                                    onPressed: () async {
                                                      String id = accountController
                                                          .following.value
                                                          .where((element) =>
                                                              element
                                                                  .providerId ==
                                                              e.providerId)
                                                          .first
                                                          .id;
                                                      print(
                                                          "lenght = ${accountController.followers.length}");
                                                      await ApiProvider(
                                                              httpClient: Dio())
                                                          .deleteProviderFollowers(
                                                              id)
                                                          .then((value) {
                                                        accountController
                                                            .following
                                                            .removeWhere((element) =>
                                                                element
                                                                    .requesterId ==
                                                                e.providerId);
                                                        accountController
                                                            .getAllFollowing();
                                                      });
                                                    },
                                                  ),
                                          )
                                        : SizedBox(),
                                  ],
                                ),
                                
                                
                        e.url.first.contains("mp4") || e.url.first.contains('MOV')
                        ? VideoWidget(
                            url: e.url.first,
                          )
                        : Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    CarouselSlider.builder(
                                      itemCount: e.url.length,
                                      itemBuilder: (context, index, realIndex) {
                                        return FancyShimmerImage(
                                          imageUrl: e.url[index],
                                          width: Get.width,
                                          boxFit: BoxFit.cover,
                                        );
                                      },
                                      options: CarouselOptions(
                                          viewportFraction: 1.0,
                                          enableInfiniteScroll: false,
                                          aspectRatio: 1 / 1,
                                          onPageChanged: (index, reason) {
                                            feedController.onPageChanged(
                                                index, reason, e.id);
                                          }),
                                    ),
                                  ],
                                ),
                                e.description != null
                                    ? Container(
                                        padding:
                                            EdgeInsets.symmetric(vertical: 8),
                                        margin: EdgeInsets.only(
                                            right: 5.0, left: 5.0),
                                        child: ReadMoreText(
                                          e.description,
                                          style:
                                              Get.textTheme.bodyText1.copyWith(
                                            fontSize: 16,
                                            fontWeight: FontWeight.w200,
                                            height: 1.3,
                                            color: e.description != null
                                                ? Colors.black
                                                : Colors.transparent,
                                          ),
                                          trimLength: 40,
                                          colorClickableText: Colors.black,
                                          trimMode: TrimMode.Length,
                                          trimCollapsedText: 'more'.tr,
                                          trimExpandedText: 'less'.tr,
                                          lessStyle: TextStyle(
                                            color: Colors.grey[400],
                                            fontSize: 14,
                                            fontWeight: FontWeight.normal,
                                          ),
                                          moreStyle: TextStyle(
                                            color: Colors.grey[400],
                                            fontSize: 14,
                                            fontWeight: FontWeight.normal,
                                          ),
                                        ),

                                        // Text(
                                        //   e.description == '_' ? '' : e.description,
                                        //   textScaleFactor: 1.0,
                                        //   style: Get.textTheme.bodyText1.copyWith(
                                        //       fontSize: 16,
                                        //       fontWeight: FontWeight.w200,
                                        //       height: 1.3),
                                        // ),
                                      )
                                    : SizedBox(),
                              ],
                            ),
                          ),
                    e.url.length > 1
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              DotsIndicator(
                                dotsCount: e.url.length,
                                position: e.index.toDouble(),
                                decorator: DotsDecorator(
                                  color: Colors.grey[300], // Inactive color
                                  activeColor: Colors.grey[600],
                                ),
                              ),
                            ],
                          )
                        : SizedBox(),
                  ],
                ),

                // Don't Touch Pls...
                Container(
                  margin: EdgeInsets.only(right: 5.0, left: 5.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          // love icon
                          Row(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  FavoriteButton(
                                    iconDisabledColor: Colors.black87,
                                    isFavorite: like,
                                    iconSize: 35,
                                    valueChanged: (like) async {
                                      print('Is Favorite : $like');
                                      if (!e.isLiked) {
                                        LikeDto likeDto = LikeDto(
                                          providerId: e.providerId,
                                          requesterId: _currentUser.id,
                                          postId: e.id,
                                        );
                                        print("providerId=${e.providerId}");
                                        print("requesterId=${_currentUser.id}");

                                        Get.log("trying to add like on feed");
                                        await ApiProvider(httpClient: Dio())
                                            .providerAddLikes(likeDto)
                                            .then((value) {
                                          feedController.feed
                                              .where((element) =>
                                                  element.id == e.id)
                                              .first
                                              .likeCount++;
                                          feedController.feed.refresh();
                                          feedController.likes.refresh();
                                          e.isLiked = true;
                                          feedController
                                              .isHeartAnimating.value = true;
                                        });
                                        await ApiProvider(httpClient: Dio())
                                            .getAllProviderLikes(e.id);
                                      } else {
                                        print('unlike');

                                        await feedLikesController
                                            .getAllProviderfeedLikes(e.id);

                                        var likeId = feedLikesController
                                            .likes.value
                                            .where((element) =>
                                                element.requesterId ==
                                                _currentUser.id)
                                            .last
                                            .id;

                                        await ApiProvider(httpClient: Dio())
                                            .providerFeedDeleteLike(likeId)
                                            .then((value) {
                                          feedController.feed
                                              .where((element) =>
                                                  element.id == e.id)
                                              .first
                                              .likeCount--;
                                          feedController.feed.refresh();
                                          feedLikesController.likes.refresh();
                                          e.isLiked = false;
                                          feedController
                                              .isHeartAnimating.value = false;
                                        });
                                      }
                                    },
                                  ),
                                  SizedBox(
                                    width: 7.0,
                                  ),
                                  // Text(
                                  //   "${e.likeCount}",
                                  //   style: Get.textTheme.bodyText1
                                  //       .copyWith(fontWeight: FontWeight.bold),
                                  // ),
                                ],
                              ),
                            ],
                          ),

                          SizedBox(width: 3.0),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              IconButton(
                                icon: SvgPicture.asset(
                                  "assets/svg/instagram-comment.svg",
                                  width: 19,
                                ),
                                onPressed: () async {
                                  Get.log("trying to get all comments");
                                  Get.lazyPut(() => FeedCommentsController());
                                  await feedcommentsController
                                      .getAllComments(e.id)
                                      .then((value) {
                                    feedcommentsController.setPostId(e.id);
                                    feedcommentsController
                                        .setPostOwner(e.providerId);
                                    Get.to(
                                      FeedComments(),
                                    );
                                  });
                                },
                              ),
                              // Text(
                              //   "${e.commentCount}",
                              //   style: Get.textTheme.bodyText1
                              //       .copyWith(fontWeight: FontWeight.bold),
                              // ),
                            ],
                          ),
                        ],
                      ),
                      e.postPrice != null
                          ? Flexible(
                              child: Ui.getPrice(e.postPrice)
                                  .paddingOnly(right: 20))
                          : SizedBox(),
                    ],
                  ),
                ),
                feedController.feed
                            .where((element) => element.id == e.id)
                            .first
                            .likeCount >
                        0
                    ? Row(
                        children: [
                          Text(
                            "Liked by".tr,
                            style: Get.theme.textTheme.bodyText2.copyWith(
                                fontWeight: FontWeight.w100, fontSize: 14),
                          ),
                          SizedBox(
                            width: 3,
                          ),
                          Text(
                            e.likeFirstName != null
                                ? e.likeFirstName
                                : _currentUser.name,
                            style: Get.theme.textTheme.bodyText2.copyWith(
                                fontWeight: FontWeight.w700, fontSize: 15),
                          ),
                          SizedBox(
                            width: 2,
                          ),
                          feedController.feed
                                      .where((element) => element.id == e.id)
                                      .first
                                      .likeCount >=
                                  2
                              ? Text(
                                  "and".tr,
                                  style: Get.theme.textTheme.bodyText2.copyWith(
                                      fontWeight: FontWeight.w100,
                                      fontSize: 12),
                                )
                              : SizedBox(),
                          SizedBox(
                            width: 2,
                          ),
                          feedController.feed
                                      .where((element) => element.id == e.id)
                                      .first
                                      .likeCount >=
                                  2
                              ? InkWell(
                                  child: IgnorePointer(
                                    child: Row(
                                      children: [
                                        Text(
                                          "${e.likeCount - 1}".tr,
                                          style: Get.theme.textTheme.bodyText2
                                              .copyWith(
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 15),
                                        ).paddingSymmetric(horizontal: 2),
                                        Text(
                                          "others".tr,
                                          style: Get.theme.textTheme.bodyText2
                                              .copyWith(
                                                  fontWeight: FontWeight.w100,
                                                  fontSize: 12),
                                        )
                                      ],
                                    ),
                                  ),
                                  onTap: () async {
                                    Get.lazyPut(() => FeedLikesController());
                                    Get.log("trying to get all likes");
                                    await feedLikesController
                                        .getAllProviderfeedLikes(e.id)
                                        .then((value) {
                                      Get.to(
                                        FeedLikes(),
                                      );
                                    });
                                  },
                                )
                              : SizedBox(),
                        ],
                      ).paddingSymmetric(horizontal: 10)
                    : SizedBox(),
                e.comments != null && e.comments.isNotEmpty
                    ? Container(
                        margin: EdgeInsets.only(
                          left: 10,
                          right: 10,
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              margin: EdgeInsets.only(top: 10.0, bottom: 5.0),
                              child: Text(
                                "Comments".tr,
                                style: Get.textTheme.bodyText1.copyWith(
                                    fontWeight: FontWeight.bold, fontSize: 14),
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "${e.comments.first.requesterName}",
                                  style: Get.textTheme.bodyText1.copyWith(
                                      fontWeight: FontWeight.w700,
                                      fontSize: 14),
                                ),
                                SizedBox(
                                  width: 2.0,
                                ),
                                Expanded(
                                  flex: 6,
                                  child: Text(
                                    e.comments.first.comments.length > 40
                                        ? String.fromCharCodes(e
                                                .comments.first.comments
                                                .replaceAll("\n", " ")
                                                .runes
                                                .toList()
                                                .sublist(0, 40)) +
                                            "..."
                                        : e.comments.first.comments
                                            .replaceAll("\n", " "),
                                    overflow: TextOverflow.ellipsis,
                                    style: Get.textTheme.bodyText1.copyWith(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w100,
                                    ),
                                  ),
                                )
                              ],
                            ),
                            e.commentCount > 1
                                ? Container(
                                    margin: EdgeInsets.only(top: 10.0),
                                    child: InkWell(
                                      child: IgnorePointer(
                                        child: RichText(
                                          overflow: TextOverflow.ellipsis,
                                          maxLines: 2,
                                          text: TextSpan(
                                            text: "See all ".tr,
                                            style: Get.textTheme.bodyText1
                                                .copyWith(
                                              fontSize: 12,
                                              fontWeight: FontWeight.w500,
                                              color: Ui.parseColor("#949494"),
                                            ),
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: " (${e.commentCount}) ",
                                                style: Get.textTheme.bodyText1
                                                    .copyWith(
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                  color:
                                                      Ui.parseColor("#949494"),
                                                ),
                                              ),
                                              TextSpan(
                                                text: "comments".tr,
                                                style: Get.textTheme.bodyText1
                                                    .copyWith(
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                  color:
                                                      Ui.parseColor("#949494"),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                      onTap: () async {
                                        Get.log("trying to get all comments");
                                        Get.lazyPut(
                                            () => FeedCommentsController());
                                        await feedcommentsController
                                            .getAllComments(e.id)
                                            .then((value) {
                                          feedcommentsController
                                              .setPostId(e.id);
                                          feedcommentsController
                                              .setPostOwner(e.providerId);
                                          Get.to(
                                            FeedComments(),
                                          );
                                        });
                                      },
                                    ),
                                  )
                                : SizedBox(),
                          ],
                        ),
                      )
                    : SizedBox(),
              ],
            ),
          )
        : SizedBox();
  }
}

class FeedVideoWidget extends StatefulWidget {
  const FeedVideoWidget({Key key, this.videoUrl, this.autoPlay})
      : super(key: key);

  final bool autoPlay;
  final String videoUrl;

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

class _FeedVideoWidgetState extends State<FeedVideoWidget> {
  VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(widget.videoUrl)
      ..initialize().then((_) {
        _controller.setLooping(widget.autoPlay);
        Future.delayed(
          Duration(
            milliseconds: 500,
          ),
          () {
            if (widget.autoPlay) {
              _controller.play();
              _controller.setVolume(0.0);
            } else {
              _controller.pause();
              _controller.setVolume(0.0);
            }

            setState(() {});
          },
        );
      });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  /*

  @override
  void didUpdateWidget(FeedVideoWidget oldWidget) {
    _controller.pause();
    _controller.setLooping(false);

    super.didUpdateWidget(oldWidget);
  }

    */

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        if (_controller.value.volume == 0.0) {
          _controller.setVolume(1.0);
        } else {
          _controller.setVolume(0.0);
        }
        setState(() {});
      },
      child: _controller.value.isInitialized
          ? Center(
              child: Stack(
                children: [
                  AspectRatio(
                    aspectRatio: 1,
                    child: VideoPlayer(_controller),
                  ),
                  widget.autoPlay
                      ? Container(
                          margin: EdgeInsets.all(5.0),
                          child: _controller.value.volume == 0.0
                              ? Icon(
                                  Icons.volume_off,
                                  color: Get.theme.primaryColor,
                                  size: 25,
                                )
                              : Icon(
                                  Icons.volume_up,
                                  color: Get.theme.primaryColor,
                                  size: 25,
                                ),
                        )
                      : Icon(
                          Icons.play_arrow,
                          color: Get.theme.primaryColor,
                          size: 25,
                        )
                ],
              ),
            )
          : Container(),
    );
  }
}

// Forbidden
class VideoWidget extends StatefulWidget {
  const VideoWidget(
      {Key key,
      @required this.url,})
      : super(key: key);

  final String url;

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

class _VideoWidgetState extends State<VideoWidget> {
  double aRatio = 0.5;
  VideoPlayerController _controller;
  ChewieController chewieController;
  Future<void> _initializeVideoPlayerFuture;

  @override
  void dispose() {
    _controller.dispose();
    chewieController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(widget.url);
    _initializeVideoPlayerFuture = _controller.initialize().then((_) {
      // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
      setState(
        () {
      aRatio = _controller.value.aspectRatio <
                  ((MediaQuery.of(context).size.width /
                          MediaQuery.of(context).size.height) +
                      0.4)
              ? _controller.value.aspectRatio / 0.7
              : _controller.value.aspectRatio;
      chewieController = ChewieController(
          videoPlayerController: _controller,
          autoPlay: false,
          looping: false,
          autoInitialize: true,
          aspectRatio: aRatio,);
              _controller.pause();
              _controller.setLooping(false);
        },
      
      );
    });

  }

  @override
  Widget build(BuildContext context) {

    return VisibilityDetector(
        key: ObjectKey(_controller),
          onVisibilityChanged: (visibility){
            if (visibility.visibleFraction == 0 && this.mounted) {
                  _controller.pause();
            }

            else 
            {
              _controller.play();
            }

       },
      child: FutureBuilder(
       future: _initializeVideoPlayerFuture,
       builder: (context, snapshot) {
         if (snapshot.connectionState == ConnectionState.done) {
           return _controller.value.isInitialized
               ? Stack(
                   children: [
                     AspectRatio(
                       aspectRatio: aRatio,
                       child: VolumeWatcher(
                         onVolumeChangeListener: (double volume) {
                           chewieController.setVolume(volume);
                         },
                         child: Chewie(
                           controller: chewieController,
                         ),
                       ),
                     ),
                   ],
                 )
               : Container();
         } else {
           return Container(
             width: double.infinity,
             height: 400,
             // child: FancyShimmerImage(
             //     imageUrl: 'https://i.imgur.com/j57mwe4.jpg'),
           );
         }
       },
          ),
    ); }
}