Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:convert';
- import 'package:coocafe_tecnico_app/helpers/notificacoes_cooperado_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/produtor_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/propriedade_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/talhao_helper.dart';
- import 'package:coocafe_tecnico_app/widgets/drawer.dart';
- import 'package:coocafe_tecnico_app/pages/notificacoes-cooperado-page.dart';
- import 'package:coocafe_tecnico_app/pages/produtor_page.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter_string_encryption/flutter_string_encryption.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:url_launcher/url_launcher.dart';
- import 'package:http/http.dart' as http;
- import 'package:date_format/date_format.dart';
- class ListaProdutorPage extends StatefulWidget {
- static String tag = "lista-produtor-page";
- static bool refresh = false;
- final PageController controller;
- ListaProdutorPage({this.controller});
- @override
- _ListaProdutorPageState createState() => _ListaProdutorPageState();
- }
- class _ListaProdutorPageState extends State<ListaProdutorPage> {
- ProdutorHelper prodHelper = ProdutorHelper();
- NotificacoesCoopHelper notCoopHelper = NotificacoesCoopHelper();
- PropriedadeHelper propriedadeHelper = PropriedadeHelper();
- TalhaoHelper talhaoHelper = TalhaoHelper();
- List<Produtor> _listaProdutor = List();
- List<NotificacoesCoop> _listaNotCoop = List();
- ScrollController _scrollCtrl = ScrollController();
- String _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
- static bool _refresh = false;
- static int progresso = 0;
- static String textProgress = "Carregando...";
- Icon actionIcon = new Icon(Icons.search);
- Widget appBarTitle = new Text("Produtores");
- String _searchText = "";
- final TextEditingController _searchQuery = new TextEditingController();
- bool _IsSearching;
- List<Produtor> _searchList = List();
- @override
- void initState() {
- super.initState();
- _IsSearching = false;
- progresso = 0;
- prodHelper.getAll().then((list) {
- _listaProdutor = list;
- });
- }
- _SearchListState() {
- _searchQuery.addListener(() {
- if(_searchQuery.text.isEmpty) {
- setState(() {
- _IsSearching = false;
- _searchText = "";
- });
- } else {
- setState(() {
- _IsSearching = true;
- _searchText = _searchQuery.text;
- });
- }
- });
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- drawer: DrawerPage(pageCtrl: widget.controller,),
- appBar: AppBar(
- title: appBarTitle,
- centerTitle: true,
- actions: <Widget>[
- IconButton(icon: actionIcon, onPressed: (){
- setState(() {
- if(this.actionIcon.icon == Icons.search) {
- this.actionIcon = new Icon(Icons.close);
- this.appBarTitle = new TextField(
- controller: _searchQuery,
- style: TextStyle(
- color: Colors.white
- ),
- decoration: InputDecoration(
- prefixIcon: Icon(Icons.search, color: Colors.white,),
- hintText: "Pesquisar...",
- hintStyle: TextStyle(color: Colors.white)
- ),
- onChanged: searchOperation,
- );
- _handleSearchStart();
- } else {
- _handleSearchEnd();
- }
- });
- },)
- ],
- ),
- floatingActionButton: FloatingActionButton(
- backgroundColor: Colors.red,
- child: Icon(Icons.keyboard_arrow_up),
- onPressed: () {
- _scrollCtrl.animateTo(0.0, duration: const Duration(milliseconds: 1), curve: Curves.easeOut);
- }
- ),
- body: Container(
- color: Colors.white,
- child: FutureBuilder(
- future: prodHelper.getAll(),
- builder: (context, snapshot) {
- switch(snapshot.connectionState) {
- case ConnectionState.none:
- case ConnectionState.waiting:
- return Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisSize: MainAxisSize.max,
- children: <Widget>[
- Container(
- width: 200.00,
- height: 200.00,
- alignment: Alignment.center,
- child: Column(
- children: <Widget>[
- CircularProgressIndicator(
- valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
- strokeWidth: 5.0,
- ),
- ],
- )
- )
- ],
- );
- break;
- default:
- if(snapshot.hasData) {
- return RefreshIndicator(
- child: _searchList.length != 0 || _searchQuery.text.isNotEmpty ?
- ListView.builder(
- padding: EdgeInsets.all(10.0),
- controller: _scrollCtrl,
- itemCount: _searchList.length,
- itemBuilder: (context, index) {
- return _createCardProdutor(context, index);
- },
- )
- : ListView.builder(
- padding: EdgeInsets.all(10.0),
- controller: _scrollCtrl,
- itemCount: _listaProdutor.length,
- itemBuilder: (context, index) {
- return _createCardProdutor(context, index);
- },
- ),
- onRefresh: _getListaProdutor,
- );
- } else if(snapshot.hasError) {
- return Container(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Icon(
- Icons.error_outline,
- size: 40.0,
- color: Colors.red,
- ),
- Center(
- child: Text(
- "Erro ao atualizar os dados!",
- style: TextStyle(fontSize: 20.0),
- ),
- )
- ],
- ),
- );
- } else {
- return Container();
- }
- break;
- }
- }
- ),
- )
- );
- }
- void _handleSearchStart() {
- setState(() {
- _IsSearching = true;
- });
- }
- void _handleSearchEnd() {
- setState(() {
- this.actionIcon = new Icon(Icons.search, color: Colors.white,);
- this.appBarTitle = new Text("Produtores", style: TextStyle(color: Colors.white),);
- _IsSearching = false;
- _searchQuery.clear();
- });
- }
- void searchOperation(String searchText) {
- String name = "";
- if(_IsSearching) {
- for(int i = 0; i < _listaProdutor.length; i++) {
- if(_listaProdutor[i].nome != null) {
- name = _listaProdutor[i].nome;
- if (name.toLowerCase().contains(searchText.toLowerCase())) {
- setState((){
- _searchList.add(_listaProdutor[i]);
- });
- }
- }
- }
- }
- }
- Widget _createCardProdutor(BuildContext context, int index) {
- return GestureDetector(
- child: Card(
- color: index % 2 == 0 ? Theme.of(context).cardColor : Colors.white70,
- child: Padding(
- padding: EdgeInsets.all(10.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Text(
- _listaProdutor[index].nome != null
- ? _listaProdutor[index].nome
- : "SEM TEXTO",
- style:
- TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
- ),
- Text(
- _listaProdutor[index].endereco != null ? _listaProdutor[index].endereco + ", " + _listaProdutor[index].numero.toString() + " - " + _listaProdutor[index].bairro + " - " + _listaProdutor[index].cidade + " - " + _listaProdutor[index].uf : "",
- style: TextStyle(fontSize: 14.0),
- ),
- Padding(
- padding: EdgeInsets.only(top: 20.0),
- child: Row(
- children: <Widget>[
- Visibility(
- visible: _listaProdutor[index].celular != null && _listaProdutor[index].celular != "0" && _listaProdutor[index].celular != "" && _listaProdutor[index].celular != " ",
- child: FlatButton(
- child: Row(
- children: <Widget>[
- Icon(
- Icons.phone,
- color: Colors.blue,
- ),
- ],
- ),
- onPressed: () async {
- await launch("tel:+55" + _listaProdutor[index].celular);
- },
- )
- ),
- FlatButton(
- child: Row(
- children: <Widget>[
- Icon(
- Icons.pin_drop,
- color: Colors.blue,
- ),
- ],
- ),
- onPressed: () {},
- ),
- FlatButton(
- child: Container(
- width: 40.0,
- child: Stack(
- children: <Widget>[
- Icon(
- Icons.notifications,
- color: Colors.blue,
- ),
- Positioned(
- top: 0.0,
- left: 13.0,
- child: Visibility(
- visible: _listaNotCoop.length > 0,
- child: Container(
- width: 15.0,
- decoration: BoxDecoration(
- color: Colors.green,
- shape: BoxShape.circle
- ),
- child: Center(
- child: Text(
- _listaNotCoop.length > 0 ? _listaNotCoop.length.toString() : _listaNotCoop.length > 9 ? "9+" : "",
- style: TextStyle(color: Colors.white, fontSize: 12.0, fontWeight: FontWeight.w500),
- ),
- )
- ),
- )
- ),
- ],
- ),
- ),
- onPressed: () async {
- await Navigator.push(context,
- MaterialPageRoute(builder: (context) => NotificacoesCooperadoPage())
- );
- },
- ),
- ],
- ),
- )
- ],
- )
- )
- ),
- onTap: () async {
- await Navigator.push(
- context,
- MaterialPageRoute(
- builder: (context) => ProdutorPage(
- produtor: _listaProdutor[index],
- )));
- },
- );
- }
- Future<List> _getListaProdutor() async {
- int totalProdutores = 0;
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Produtor> lista = List();
- List<Propriedade> propriedades = List();
- String usuario = prefs.get("user");
- String senha = prefs.get("pass");
- String key = prefs.get("key");
- final cryptor = new PlatformStringCryptor();
- final String encrypted = await cryptor.decrypt(senha, key);
- Map dados = {"user": usuario, "password": encrypted};
- String ldados = json.encode(dados);
- http.Response response = await http.post(
- 'http://coocafe.com.br/vSite/views/soap/app_tecnico/produtor.php',
- body: ldados);
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != null && retorno["status"] != "") {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaProdutor = retorno['lista'];
- totalProdutores = listaProdutor.length;
- await prodHelper.deleteAll();
- await propriedadeHelper.deleteAll();
- await talhaoHelper.deleteAll();
- for (Map itens in listaProdutor) {
- Produtor prod = Produtor();
- prod = await prodHelper.saveProdutor(Produtor.fromMap(itens));
- lista.add(prod);
- /*if(listaPropriedades['talhao'].toString().startsWith("[")) {
- var listaTalhao = listaPropriedades['talhao'];
- for(Map tal in listaTalhao) {
- Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
- print("Talhão " + talhao.Codigo.toString() + " inderido com sucesso!");
- }
- } else {
- var talhao = listaPropriedades['talhao'];
- Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
- print("Talhão " + tal.Codigo.toString() + " inderido com sucesso!");
- }*/
- /**/
- }
- for (Map itens in listaProdutor) {
- var listaPropriedades = itens['propriedade'];
- if(itens['propriedade'].toString().startsWith("[")) {
- //É uma lista
- var listaProp = itens['propriedade'];
- for(Map prop in listaProp) {
- Propriedade propi = await propriedadeHelper.savePropriedade(Propriedade.fromMap(prop));
- }
- } else {
- //É um objeto
- var propriedades = itens['propriedade'];
- Propriedade prop = await propriedadeHelper.savePropriedade(Propriedade.fromMap(propriedades));
- }
- for (Map itens in listaPropriedades) {
- var listaTalhao = itens['talhao'];
- if(itens['talhao'].toString().startsWith("[")) {
- //É uma lista
- var listaTalhao = itens['talhao'];
- for (Map tal in listaTalhao) {
- Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
- }
- } else {
- //É um objeto
- var tal = itens['talhao'];
- Talhao talhao = await talhaoHelper.saveTalhao(Talhao.fromMap(tal));
- }
- }
- }
- }
- return lista;
- }
- void _showDialog(BuildContext context, String texto) {
- // flutter defined function
- showDialog(
- context: context,
- builder: (BuildContext context) {
- // return object of type Dialog
- return AlertDialog(
- title: new Text("Atenção"),
- content: new Text(texto),
- actions: <Widget>[
- // usually buttons at the bottom of the dialog
- new FlatButton(
- child: new Text("OK"),
- onPressed: () {
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment