danielbrito1987

lista-produtor-page

Oct 29th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 16.86 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:coocafe_tecnico_app/helpers/notificacoes_cooperado_helper.dart';
  4. import 'package:coocafe_tecnico_app/helpers/produtor_helper.dart';
  5. import 'package:coocafe_tecnico_app/helpers/propriedade_helper.dart';
  6. import 'package:coocafe_tecnico_app/helpers/talhao_helper.dart';
  7. import 'package:coocafe_tecnico_app/widgets/drawer.dart';
  8. import 'package:coocafe_tecnico_app/pages/notificacoes-cooperado-page.dart';
  9. import 'package:coocafe_tecnico_app/pages/produtor_page.dart';
  10. import 'package:flutter/material.dart';
  11. import 'package:flutter_string_encryption/flutter_string_encryption.dart';
  12. import 'package:shared_preferences/shared_preferences.dart';
  13. import 'package:url_launcher/url_launcher.dart';
  14. import 'package:http/http.dart' as http;
  15. import 'package:date_format/date_format.dart';
  16.  
  17. class ListaProdutorPage extends StatefulWidget {
  18.   static String tag = "lista-produtor-page";
  19.   static bool refresh = false;
  20.   final PageController controller;
  21.  
  22.   ListaProdutorPage({this.controller});
  23.  
  24.   @override
  25.   _ListaProdutorPageState createState() => _ListaProdutorPageState();
  26. }
  27.  
  28. class _ListaProdutorPageState extends State<ListaProdutorPage> {
  29.   ProdutorHelper prodHelper = ProdutorHelper();
  30.   NotificacoesCoopHelper notCoopHelper = NotificacoesCoopHelper();
  31.   PropriedadeHelper propriedadeHelper = PropriedadeHelper();
  32.   TalhaoHelper talhaoHelper = TalhaoHelper();
  33.   List<Produtor> _listaProdutor = List();
  34.   List<NotificacoesCoop> _listaNotCoop = List();
  35.   ScrollController _scrollCtrl = ScrollController();
  36.   String _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
  37.   static bool _refresh = false;
  38.   static int progresso = 0;
  39.   static String textProgress = "Carregando...";
  40.   Icon actionIcon = new Icon(Icons.search);
  41.   Widget appBarTitle = new Text("Produtores");
  42.   String _searchText = "";
  43.   final TextEditingController _searchQuery = new TextEditingController();
  44.   bool _IsSearching;
  45.   List<Produtor> _searchList = List();
  46.  
  47.   @override
  48.   void initState() {
  49.     super.initState();
  50.  
  51.     _IsSearching = false;
  52.  
  53.     progresso = 0;
  54.  
  55.     prodHelper.getAll().then((list) {
  56.       _listaProdutor = list;
  57.     });
  58.   }
  59.  
  60.   _SearchListState() {
  61.     _searchQuery.addListener(() {
  62.       if(_searchQuery.text.isEmpty) {
  63.         setState(() {
  64.           _IsSearching = false;
  65.           _searchText = "";
  66.         });
  67.       } else {
  68.         setState(() {
  69.           _IsSearching = true;
  70.           _searchText = _searchQuery.text;
  71.         });
  72.       }
  73.     });
  74.   }
  75.  
  76.   @override
  77.   Widget build(BuildContext context) {
  78.     return Scaffold(
  79.         drawer: DrawerPage(pageCtrl: widget.controller,),
  80.         appBar: AppBar(
  81.           title: appBarTitle,
  82.           centerTitle: true,
  83.           actions: <Widget>[
  84.             IconButton(icon: actionIcon, onPressed: (){
  85.               setState(() {
  86.                 if(this.actionIcon.icon == Icons.search) {
  87.                   this.actionIcon = new Icon(Icons.close);
  88.                   this.appBarTitle = new TextField(
  89.                     controller: _searchQuery,
  90.                     style: TextStyle(
  91.                       color: Colors.white
  92.                     ),
  93.                     decoration: InputDecoration(
  94.                       prefixIcon: Icon(Icons.search, color: Colors.white,),
  95.                       hintText: "Pesquisar...",
  96.                       hintStyle: TextStyle(color: Colors.white)
  97.                     ),
  98.                     onChanged: searchOperation,
  99.                   );
  100.                   _handleSearchStart();
  101.                 } else {
  102.                   _handleSearchEnd();
  103.                 }
  104.               });
  105.             },)
  106.           ],
  107.         ),
  108.         floatingActionButton: FloatingActionButton(
  109.             backgroundColor: Colors.red,
  110.             child: Icon(Icons.keyboard_arrow_up),
  111.             onPressed: () {
  112.               _scrollCtrl.animateTo(0.0, duration: const Duration(milliseconds: 1), curve: Curves.easeOut);
  113.             }
  114.         ),
  115.         body: Container(
  116.           color: Colors.white,
  117.           child: FutureBuilder(
  118.               future: prodHelper.getAll(),
  119.               builder: (context, snapshot) {
  120.                 switch(snapshot.connectionState) {
  121.                   case ConnectionState.none:
  122.                   case ConnectionState.waiting:
  123.                     return Column(
  124.                       mainAxisAlignment: MainAxisAlignment.center,
  125.                       crossAxisAlignment: CrossAxisAlignment.stretch,
  126.                       mainAxisSize: MainAxisSize.max,
  127.                       children: <Widget>[
  128.                         Container(
  129.                           width: 200.00,
  130.                           height: 200.00,
  131.                           alignment: Alignment.center,
  132.                           child: Column(
  133.                             children: <Widget>[
  134.                               CircularProgressIndicator(
  135.                                 valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
  136.                                 strokeWidth: 5.0,
  137.                               ),
  138.                             ],
  139.                           )
  140.                         )
  141.                       ],
  142.                     );
  143.                     break;
  144.                   default:
  145.                     if(snapshot.hasData) {
  146.                       return RefreshIndicator(
  147.                         child: _searchList.length != 0 || _searchQuery.text.isNotEmpty ?
  148.                         ListView.builder(
  149.                           padding: EdgeInsets.all(10.0),
  150.                           controller: _scrollCtrl,
  151.                           itemCount: _searchList.length,
  152.                           itemBuilder: (context, index) {
  153.                             return _createCardProdutor(context, index);
  154.                           },
  155.                         )
  156.                         : ListView.builder(
  157.                             padding: EdgeInsets.all(10.0),
  158.                             controller: _scrollCtrl,
  159.                             itemCount: _listaProdutor.length,
  160.                             itemBuilder: (context, index) {
  161.                               return _createCardProdutor(context, index);
  162.                             },
  163.                           ),
  164.                         onRefresh: _getListaProdutor,
  165.                       );
  166.                     } else if(snapshot.hasError) {
  167.                       return Container(
  168.                         child: Column(
  169.                           crossAxisAlignment: CrossAxisAlignment.stretch,
  170.                           mainAxisAlignment: MainAxisAlignment.center,
  171.                           children: <Widget>[
  172.                             Icon(
  173.                               Icons.error_outline,
  174.                               size: 40.0,
  175.                               color: Colors.red,
  176.                             ),
  177.                             Center(
  178.                               child: Text(
  179.                                 "Erro ao atualizar os dados!",
  180.                                 style: TextStyle(fontSize: 20.0),
  181.                               ),
  182.                             )
  183.                           ],
  184.                         ),
  185.                       );
  186.                     } else {
  187.                       return Container();
  188.                     }
  189.                     break;
  190.                 }
  191.               }
  192.           ),
  193.         )
  194.     );
  195.   }
  196.  
  197.   void _handleSearchStart() {
  198.     setState(() {
  199.       _IsSearching = true;
  200.     });
  201.   }
  202.  
  203.   void _handleSearchEnd() {
  204.     setState(() {
  205.       this.actionIcon = new Icon(Icons.search, color: Colors.white,);
  206.       this.appBarTitle = new Text("Produtores", style: TextStyle(color: Colors.white),);
  207.       _IsSearching = false;
  208.       _searchQuery.clear();
  209.     });
  210.   }
  211.  
  212.   void searchOperation(String searchText) {
  213.     String name = "";
  214.     if(_IsSearching) {
  215.       for(int i = 0; i < _listaProdutor.length; i++) {
  216.         if(_listaProdutor[i].nome != null) {
  217.           name = _listaProdutor[i].nome;
  218.  
  219.           if (name.toLowerCase().contains(searchText.toLowerCase())) {
  220.             setState((){
  221.               _searchList.add(_listaProdutor[i]);
  222.             });
  223.           }
  224.         }
  225.       }
  226.     }
  227.   }
  228.  
  229.   Widget _createCardProdutor(BuildContext context, int index) {
  230.     return GestureDetector(
  231.       child: Card(
  232.           color: index % 2 == 0 ? Theme.of(context).cardColor : Colors.white70,
  233.           child: Padding(
  234.               padding: EdgeInsets.all(10.0),
  235.               child: Column(
  236.                 crossAxisAlignment: CrossAxisAlignment.start,
  237.                 children: <Widget>[
  238.                   Text(
  239.                     _listaProdutor[index].nome != null
  240.                         ? _listaProdutor[index].nome
  241.                         : "SEM TEXTO",
  242.                     style:
  243.                     TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
  244.                   ),
  245.                   Text(
  246.                     _listaProdutor[index].endereco != null ? _listaProdutor[index].endereco + ", " + _listaProdutor[index].numero.toString() + " - " + _listaProdutor[index].bairro + " - " + _listaProdutor[index].cidade + " - " + _listaProdutor[index].uf : "",
  247.                     style: TextStyle(fontSize: 14.0),
  248.                   ),
  249.                   Padding(
  250.                     padding: EdgeInsets.only(top: 20.0),
  251.                     child: Row(
  252.                       children: <Widget>[
  253.                         Visibility(
  254.                             visible: _listaProdutor[index].celular != null && _listaProdutor[index].celular != "0" && _listaProdutor[index].celular != "" && _listaProdutor[index].celular != " ",
  255.                             child: FlatButton(
  256.                               child: Row(
  257.                                 children: <Widget>[
  258.                                   Icon(
  259.                                     Icons.phone,
  260.                                     color: Colors.blue,
  261.                                   ),
  262.                                 ],
  263.                               ),
  264.                               onPressed: () async {
  265.                                 await launch("tel:+55" + _listaProdutor[index].celular);
  266.                               },
  267.                             )
  268.                         ),
  269.                         FlatButton(
  270.                           child: Row(
  271.                             children: <Widget>[
  272.                               Icon(
  273.                                 Icons.pin_drop,
  274.                                 color: Colors.blue,
  275.                               ),
  276.                             ],
  277.                           ),
  278.                           onPressed: () {},
  279.                         ),
  280.                         FlatButton(
  281.                           child: Container(
  282.                             width: 40.0,
  283.                             child: Stack(
  284.                               children: <Widget>[
  285.                                 Icon(
  286.                                   Icons.notifications,
  287.                                   color: Colors.blue,
  288.                                 ),
  289.                                 Positioned(
  290.                                   top: 0.0,
  291.                                   left: 13.0,
  292.                                   child: Visibility(
  293.                                     visible: _listaNotCoop.length > 0,
  294.                                     child: Container(
  295.                                         width: 15.0,
  296.                                         decoration: BoxDecoration(
  297.                                             color: Colors.green,
  298.                                             shape: BoxShape.circle
  299.                                         ),
  300.                                         child: Center(
  301.                                           child: Text(
  302.                                             _listaNotCoop.length > 0 ? _listaNotCoop.length.toString() : _listaNotCoop.length > 9 ? "9+" : "",
  303.                                             style: TextStyle(color: Colors.white, fontSize: 12.0, fontWeight: FontWeight.w500),
  304.                                           ),
  305.                                         )
  306.                                     ),
  307.                                   )
  308.                                 ),
  309.                               ],
  310.                             ),
  311.                           ),
  312.                           onPressed: () async {
  313.                             await Navigator.push(context,
  314.                                 MaterialPageRoute(builder: (context) => NotificacoesCooperadoPage())
  315.                             );
  316.                           },
  317.                         ),
  318.                       ],
  319.                     ),
  320.                   )
  321.                 ],
  322.               )
  323.           )
  324.       ),
  325.       onTap: () async {
  326.         await Navigator.push(
  327.             context,
  328.             MaterialPageRoute(
  329.                 builder: (context) => ProdutorPage(
  330.                   produtor: _listaProdutor[index],
  331.                 )));
  332.       },
  333.     );
  334.   }
  335.  
  336.   Future<List> _getListaProdutor() async {
  337.     int totalProdutores = 0;
  338.  
  339.     Map<String, dynamic> myMap = Map();
  340.     SharedPreferences prefs = await SharedPreferences.getInstance();
  341.     List<Produtor> lista = List();
  342.     List<Propriedade> propriedades = List();
  343.  
  344.     String usuario = prefs.get("user");
  345.     String senha = prefs.get("pass");
  346.     String key = prefs.get("key");
  347.  
  348.     final cryptor = new PlatformStringCryptor();
  349.     final String encrypted = await cryptor.decrypt(senha, key);
  350.  
  351.     Map dados = {"user": usuario, "password": encrypted};
  352.     String ldados = json.encode(dados);
  353.  
  354.     http.Response response = await http.post(
  355.         'http://coocafe.com.br/vSite/views/soap/app_tecnico/produtor.php',
  356.         body: ldados);
  357.  
  358.     Map<String, dynamic> retorno = json.decode(response.body);
  359.  
  360.     if (retorno["status"] != null && retorno["status"] != "") {
  361.       _showDialog(context, "Erro ao processar a requisição.");
  362.     } else {
  363.       var listaProdutor = retorno['lista'];
  364.       totalProdutores = listaProdutor.length;
  365.  
  366.       await prodHelper.deleteAll();
  367.       await propriedadeHelper.deleteAll();
  368.       await talhaoHelper.deleteAll();
  369.  
  370.       for (Map itens in listaProdutor) {
  371.  
  372.         Produtor prod = Produtor();
  373.  
  374.         prod = await prodHelper.saveProdutor(Produtor.fromMap(itens));
  375.  
  376.         lista.add(prod);
  377.  
  378.         /*if(listaPropriedades['talhao'].toString().startsWith("[")) {
  379.           var listaTalhao = listaPropriedades['talhao'];
  380.  
  381.           for(Map tal in listaTalhao) {
  382.             Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
  383.  
  384.             print("Talhão " + talhao.Codigo.toString() + " inderido com sucesso!");
  385.           }
  386.         } else {
  387.           var talhao = listaPropriedades['talhao'];
  388.  
  389.           Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
  390.  
  391.           print("Talhão " + tal.Codigo.toString() + " inderido com sucesso!");
  392.         }*/
  393.  
  394.         /**/
  395.       }
  396.  
  397.       for (Map itens in listaProdutor) {
  398.         var listaPropriedades = itens['propriedade'];
  399.  
  400.         if(itens['propriedade'].toString().startsWith("[")) {
  401.           //É uma lista
  402.           var listaProp = itens['propriedade'];
  403.  
  404.           for(Map prop in listaProp) {
  405.             Propriedade propi = await propriedadeHelper.savePropriedade(Propriedade.fromMap(prop));
  406.           }
  407.         } else {
  408.           //É um objeto
  409.           var propriedades = itens['propriedade'];
  410.  
  411.           Propriedade prop = await propriedadeHelper.savePropriedade(Propriedade.fromMap(propriedades));
  412.         }
  413.  
  414.         for (Map itens in listaPropriedades) {
  415.           var listaTalhao = itens['talhao'];
  416.  
  417.           if(itens['talhao'].toString().startsWith("[")) {
  418.             //É uma lista
  419.             var listaTalhao = itens['talhao'];
  420.  
  421.             for (Map tal in listaTalhao) {
  422.               Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
  423.             }
  424.           } else {
  425.             //É um objeto
  426.             var tal = itens['talhao'];
  427.  
  428.             Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
  429.           }
  430.         }
  431.       }
  432.     }
  433.  
  434.     return lista;
  435.   }
  436.  
  437.   void _showDialog(BuildContext context, String texto) {
  438.     // flutter defined function
  439.     showDialog(
  440.       context: context,
  441.       builder: (BuildContext context) {
  442.         // return object of type Dialog
  443.         return AlertDialog(
  444.           title: new Text("Atenção"),
  445.           content: new Text(texto),
  446.           actions: <Widget>[
  447.             // usually buttons at the bottom of the dialog
  448.             new FlatButton(
  449.               child: new Text("OK"),
  450.               onPressed: () {
  451.                 Navigator.of(context).pop();
  452.               },
  453.             ),
  454.           ],
  455.         );
  456.       },
  457.     );
  458.   }
  459.  
  460. }
Advertisement
Add Comment
Please, Sign In to add comment