Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
7.8 kB
7
Indexable
Never
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:cuongphimnews/core/util/index.dart';
import 'package:cuongphimnews/features/home/domain/entities/post_entity.dart';
import 'package:cuongphimnews/features/home/param/detail_post_param.dart';
import 'package:cuongphimnews/features/home/presentation/pages/detail_page.dart';
import 'package:cuongphimnews/features/home/presentation/riverpod/post_provider.dart';
import 'package:cuongphimnews/features/home/presentation/widgets/content_item.dart';
import 'package:cuongphimnews/features/home/presentation/widgets/custom_app_bar.dart';
import 'package:cuongphimnews/features/home/presentation/widgets/home_header_text.dart';
import 'package:cuongphimnews/features/home/presentation/widgets/slider_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({
    Key? key,
    this.homeController,
  }) : super(key: key);
  final ScrollController? homeController;
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  int oldLength = 0;
  double aspectHeight = 0, aspectWidth = 0;
  bool isCheck = false;
  ScrollController controller = ScrollController();
  @override
  void initState() {
    super.initState();
    controller = widget.homeController ?? ScrollController();
    controller.addListener(() {
      if (controller.position.pixels >
          controller.position.maxScrollExtent -
              MediaQuery.of(context).size.height) {
        if (oldLength == ref.read(postProvider).listPosts?.length) {
          ref.read(postProvider.notifier).loadMorePosts();
        }
      }
    });
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) => initPlugin());
  }

  Future<void> initPlugin() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      final TrackingStatus status =
          await AppTrackingTransparency.trackingAuthorizationStatus;

      if (status == TrackingStatus.notDetermined) {
        await AppTrackingTransparency.requestTrackingAuthorization();
      }
    } on PlatformException {
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    print('Build Home_Page');
    return Scaffold(
      appBar: CustomAppBar(
        appBar: AppBar(),
        title: 'TRANG CHỦ',
        isShowSearchButton: true,
      ),
      body: Consumer(
        builder: (ctx, watch, child) {
          final isLoadMoreError = ref.watch(postProvider).isLoadMoreError;
          final isLoadMoreDone = ref.watch(postProvider).isLoadMoreDone;
          final isLoading = ref.watch(postProvider).isLoading;
          final isLoadingPosts = ref.watch(postProvider).isLoadingPosts;
          final state = ref.watch(postProvider);
          aspectHeight = (MediaQuery.of(context).size.width - 12 * 4) / 1.79;
          aspectWidth = (MediaQuery.of(context).size.width - 12 * 4);
          oldLength = state.listPosts?.length ?? 0;

          if (state.listPosts == null) {
            if (isLoadingPosts == false) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Center(
                      child: Text('Lỗi'),
                    ),
                    ElevatedButton(
                        onPressed: () {
                          ref.read(postProvider.notifier).refresh();
                        },
                        child: Text(
                          'Tải lại trang',
                          style:
                              Theme.of(context).textTheme.bodyText2?.copyWith(
                                    color: kPrimaryColor,
                                  ),
                        ))
                  ],
                ),
              );
            }
            return const _Loading();
          }

          if (isLoading) {
            return const _Loading();
          }

          return RefreshIndicator(
            onRefresh: () {
              return ref.read(postProvider.notifier).refresh();
            },
            child: Scrollbar(
              controller: controller,
              child: CustomScrollView(
                controller: controller,
                slivers: [
                  _sliverHeaderHomePage(state),
                  _sliverListPosts(
                      state, isLoadMoreError, isLoadMoreDone, context)
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  SliverPadding _sliverListPosts(PostState state, bool isLoadMoreError,
      bool isLoadMoreDone, BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.only(
        left: 12,
        right: 12,
        top: 10.h,
        bottom: 30.h,
      ),
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          (_, i) {
            if (i == state.listPosts?.length) {
              // load more and get error
              if (isLoadMoreError) {
                return const Center(
                  child: Text('Đã có lỗi xảy ra'),
                );
              }

              if (isLoadMoreDone) {
                return const Center(
                  child: Text(
                    'Đã đến cuối trang',
                    style: TextStyle(color: Colors.green, fontSize: 20),
                  ),
                );
              }
              return const LinearProgressIndicator();
            }
            return Padding(
              padding: EdgeInsets.only(bottom: 15.h),
              child: Container(
                color: Colors.blue,
                height: 200,
                width: 200,
              ),
            );
          },
          childCount: (state.listPosts?.length ?? 0) + 1,
        ),
      ),
    );
  }

  // ContentItem(
  //               yoastHeadJson: state.listPosts?[i].yoastHeadJson,
  //               date: state.listPosts?[i].date,
  //               height: aspectHeight,
  //               width: aspectWidth,
  //               postEntity: state.listPosts?[i] ?? const PostEntity(),
  //               onTap: () {
  //                 Navigator.of(context).pushNamed(
  //                   DetailPage.route,
  //                   arguments: DetailPostParam(
  //                     currentPage: state.page,
  //                     currentIndex: i,
  //                     listPosts: state.listPosts,
  //                     currentPost: state.listPosts?[i],
  //                   ),
  //                 );
  //               },
  //             )

  SliverPadding _sliverHeaderHomePage(PostState state) {
    return SliverPadding(
      padding: EdgeInsets.all(0.h),
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 20.h),
                const HomeHeaderText(),
                SizedBox(height: 20.h),
                // SliderImage(
                //   topFivePosts: state.listTop5Posts,
                // ),
                SizedBox(height: 20.h),
              ],
            );
          },
          childCount: 1,
        ),
      ),
    );
  }
}

class _Loading extends StatelessWidget {
  const _Loading();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: CircularProgressIndicator(),
    );
  }
}