HomePage

mail@pastecode.io avatar
unknown
dart
2 years ago
6.8 kB
2
Indexable
Never
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:move_to_background/move_to_background.dart';
import 'package:t2_market/src/Controllers/FiltersController.dart';
import 'package:t2_market/src/Controllers/ProductsController.dart';
import 'package:t2_market/src/Model/ProdutoItemTabelaPreco/ProdutoItemTabelaPreco.dart';
import 'package:t2_market/src/Templates/Components/LoaderShimmers.dart';
import 'package:t2_market/src/Templates/Mobile/Categories/Categories.dart';
import 'package:t2_market/src/Templates/Mobile/Products/Filter/Filter.dart';
import 'package:t2_market/src/Templates/Mobile/Products/ProdutoBody.dart';
import 'package:t2_market/src/Templates/Web/AppBar/appBar.dart';
import 'package:t2_market/src/Templates/Mobile/ProdutosMix/ProdutosMixRow.dart';

import '../../../core/AppTextStyles.dart';

StreamController<bool> homeStream = StreamController<bool>.broadcast();

class HomePage extends StatefulWidget {
  final Stream<bool> stream;
  HomePage({Key? key, required this.stream}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  List<ProdutoItemTabelaPreco> listProdutoItemTabelaPreco = [];
  int currentPage = 1;
  bool loading = false;
  bool finished = false;

  late final ScrollController _controller;
  var visible = true;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _getData(clean: true);
    _controller.addListener(() async {
      if (_controller.position.pixels == _controller.position.maxScrollExtent &&
          !loading &&
          !finished) {
        currentPage++;
        _getData();
      }
    });
    widget.stream.listen((index) {
      setState(() {
        currentPage = 1;
      });
      _getData(clean: index);
    });
  }

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



  void _getData({bool? clean}) async {
    setState(() {
      loading = true;
    });

    if (clean == true) FiltersController.cleanFilters();

    var list = await ProductsController.fillProdutoList(page: currentPage);

    list.isEmpty
        ? setState(() {
            finished = true;
          })
        : list.forEach((e) => {
              if (e.itemTabelaPreco != null)
                {
                  setState(() {
                    listProdutoItemTabelaPreco.add(e);
                  })
                }
            });

    setState(() {
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    var screenSizeW = MediaQuery.of(context).size.width;
    return WillPopScope(
      onWillPop: () async {
        MoveToBackground.moveTaskToBack();
        return false;
      },
      child: Scaffold(
          appBar: appBar(context),
          body: loading
              ? Center(
                  child: CircularProgressIndicator(color: AppStyles.topRed),
                )
              : SingleChildScrollView(
                  controller: _controller,
                  physics: BouncingScrollPhysics(),
                  child: Column(
                    children: [
                      SizedBox(height: 10),
                      Categories(streamController.stream),
                      ProdutosMixRow(),
                      SizedBox(height: 10),
                      filtersRow(),
                      Padding(
                        padding: EdgeInsets.only(top: 10, bottom: 20),
                        child: Container(
                            child: ProdutoBody(
                                listProdutoItemTabelaPreco, loading)),
                      ),
                    ],
                  ))),
    );
  }

  Widget pagination() {
    return Padding(
      padding: EdgeInsets.only(bottom: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
              icon: Icon(Icons.arrow_left),
              onPressed: currentPage <= 1
                  ? null
                  : () {
                      setState(() {
                        currentPage -= 1;
                      });
                      _getData();
                    }),
          Text('$currentPage'),
          IconButton(
              icon: Icon(Icons.arrow_right),
              onPressed: listProdutoItemTabelaPreco.isEmpty
                  ? null
                  : () {
                      setState(() {
                        currentPage += 1;
                      });
                      _getData();
                    })
        ],
      ),
    );
  }

  Row filtersRow() {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
      Padding(
          padding: EdgeInsets.only(left: 20),
          child: Text('Produtos',
              style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).primaryTextTheme.headline1!.color))),
      Row(children: [
        IconButton(icon: Icon(Icons.filter_list), onPressed: filterDialog),
        IconButton(icon: Icon(Icons.filter_alt), onPressed: filterPage),
      ])
    ]);
  }

  dynamic filterDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            content: Container(
                child: SingleChildScrollView(
                    child: Column(children: [
          buttonFilter('A-Z', 'Nome', 'asc', '20'),
          buttonFilter('Z-A', 'Nome', 'desc', '20'),
          buttonFilter('Preço maior para menor', 'ValorVenda', 'desc', '20'),
          buttonFilter('Preço menor para maior', 'ValorVenda', 'asc', '20'),
          buttonFilter('Produtos em promoção', 'Promocao', 'desc', '20'),
        ]))));
      },
    );
  }

  Widget buttonFilter(title, field, order, quantity) {
    return TextButton(
        onPressed: () async {
          setState(() {
            listProdutoItemTabelaPreco = [];
          });
          Navigator.pop(context);
          if (field == 'Promocao') {
            await FiltersController.filterPromo();
          } else {
            await FiltersController.filter(field, order, quantity);
          }
          _getData();
        },
        child: Text(
          title,
          style: TextStyle(color: Colors.black),
        ));
  }

  dynamic filterPage() async {
    await Navigator.of(context)
        .push(MaterialPageRoute(builder: (context) => Filter()));
    setState(() {
      listProdutoItemTabelaPreco = [];
    });
    _getData();
  }
}