Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:convert';
- import 'dart:io';
- import 'dart:isolate';
- import 'dart:typed_data';
- import 'package:coocafe_tecnico_app/helpers/cultura_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/notificacao_propriedade_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/notificacoes_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/produtor_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/filial_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/propriedade_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/safra_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/talhao_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/tipo_titulo_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/notificacoes_cooperado_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/titulos_cp_helper.dart';
- import 'package:coocafe_tecnico_app/helpers/titulos_cr_helper.dart';
- import 'package:coocafe_tecnico_app/widgets/customShowDialog.dart';
- import 'package:coocafe_tecnico_app/widgets/drawer.dart';
- import 'package:coocafe_tecnico_app/pages/lista-produtor-page.dart';
- import 'package:coocafe_tecnico_app/pages/login_page.dart';
- import 'package:coocafe_tecnico_app/pages/notificacoes-page.dart';
- import 'package:coocafe_tecnico_app/pages/produtor_page.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.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';
- //import 'package:html/parser.dart' show parse;
- import 'package:connectivity/connectivity.dart';
- import 'package:screen/screen.dart';
- import 'package:modal_progress_hud/modal_progress_hud.dart';
- class HomePage extends StatefulWidget {
- static String tag = "home-page";
- final bool refreshDrawer;
- HomePage({this.refreshDrawer});
- @override
- _HomePageState createState() => _HomePageState();
- }
- class _HomePageState extends State<HomePage> {
- final String url = 'http://coocafe.com.br/vSite/views/soap/app_tecnico/hom/';
- //final String url = 'http://coocafe.com.br/vSite/views/soap/app_tecnico/prod/';
- PageController _pageCtrl = new PageController();
- ProdutorHelper prodHelper = ProdutorHelper();
- FilialHelper filialHelper = FilialHelper();
- TipoTituloHelper tipoTituloHelper = TipoTituloHelper();
- PropriedadeHelper propriedadeHelper = PropriedadeHelper();
- TalhaoHelper talhaoHelper = TalhaoHelper();
- SafraHelper safraHelper = SafraHelper();
- CulturaHelper culturaHelper = CulturaHelper();
- NotificacoesCoopHelper notProdutorHelper = NotificacoesCoopHelper();
- TitulosCRHelper titCRHelper = TitulosCRHelper();
- TitulosCPHelper titCPHelper = TitulosCPHelper();
- NotificacoesHelper notificacoesHelper = NotificacoesHelper();
- NotificacoesPropHelper notPropriedadeHelper = NotificacoesPropHelper();
- List<Produtor> _listaProdutor = List();
- ScrollController _scrollCtrl = ScrollController();
- String _dataRefresh = "";
- static int _qtdNot;
- static int progresso;
- static String textProgress = "Requisitando dados...";
- static bool _refresh = false;
- bool _refreshDrawer = false;
- static Future<List<Produtor>> tempList;
- String _connectionStatus = "Unknown";
- final Connectivity _connectivity = Connectivity();
- StreamSubscription<ConnectivityResult> _connectivitySubscription;
- ListaProdutorPage pageListaProdutor;
- NotificacoesPage pageNotificacoes = NotificacoesPage();
- bool _isRefreshing;
- @override
- void initState() {
- _isRefreshing = false;
- //WidgetsBinding.instance.addObserver(this);
- initConnectivity();
- _connectivitySubscription =
- _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
- setState(() => _connectionStatus = result.toString());
- });
- _refresh = false;
- progresso = 0;
- SharedPreferences.getInstance().then((data) {
- if(data.getString("TextoAtualizacao") != null) {
- _dataRefresh = data.getString("TextoAtualizacao");
- }
- });
- filialHelper.getAll().then((list) {
- if (list.length <= 0) _getListaFilial().then((filiais) {});
- });
- safraHelper.getAll().then((list) {
- if (list.length <= 0) _getListaSafra().then((safras) {});
- });
- culturaHelper.getAll().then((list) {
- if (list.length <= 0) _getListaCultura().then((culturas) {});
- });
- tipoTituloHelper.getAll().then((list) {
- if (list.length <= 0) _getListaTipoTitulo().then((tipos) {});
- });
- notificacoesHelper.getAll().then((list) {
- if (list.length <= 0) _getListaNotificacoesTecnico().then((notificacoes) {});
- });
- tempList = _getListaProdutorLocal();
- _refreshDrawer = widget.refreshDrawer != null ? widget.refreshDrawer : false;
- if(_refreshDrawer) {
- setState(() {
- _isRefreshing = true;
- progresso = 0;
- textProgress = "Requisitando dados...";
- _atualizarTalhoes();
- });
- }
- notificacoesHelper.getCountNotificacaoTec().then((value) {
- setState(() {
- _qtdNot = value;
- pageListaProdutor = ListaProdutorPage(controller: _pageCtrl, qtdNot: _qtdNot,);
- });
- });
- super.initState();
- }
- @override
- void dispose() {
- _connectivitySubscription.cancel();
- super.dispose();
- }
- @override
- Widget build(BuildContext context) {
- //print('Estado do app: $_lastLifecycleState.');
- return WillPopScope(
- child: PageView(
- controller: _pageCtrl,
- physics: NeverScrollableScrollPhysics(),
- children: <Widget>[
- Scaffold(
- backgroundColor: Colors.white,
- drawer: DrawerPage(pageCtrl: _pageCtrl, qtdNot: _qtdNot,),
- appBar: AppBar(
- title: Text("App Técnico"),
- centerTitle: true,
- actions: <Widget>[
- ButtonTheme(
- minWidth: 44.0,
- padding: EdgeInsets.all(0.0),
- child: ButtonBar(
- children: <Widget>[
- FlatButton(
- child: IconTheme(
- data: IconThemeData(color: Colors.white),
- child: Icon(Icons.refresh),
- ),
- onPressed: () async {
- if(_connectionStatus == "ConnectivityResult.none") {
- showDialog(
- context: context,
- barrierDismissible: false,
- builder: (BuildContext context) {
- return CustomAlertDialog(
- title: Text("Atenção!"),
- content: Text("Sem conexão no momento. Tente novamente com o dispositivo conectado à internet."),
- actions: <Widget>[
- FlatButton(
- child: Text("OK"),
- onPressed: () {
- Navigator.of(context).pop();
- },
- )
- ],
- );
- }
- );
- } else if(!_isRefreshing) {
- showDialog(
- context: context,
- barrierDismissible: false,
- builder: (BuildContext context) {
- return CustomAlertDialog(
- title: Text("Sincronizar Dados"),
- content: Text("Deseja sincronizar os dados com o servidor?"),
- actions: <Widget>[
- FlatButton(
- child: Text("Sim"),
- onPressed: () async {
- Navigator.of(context).pop();
- try {
- Screen.keepOn(true);
- setState(() async {
- _isRefreshing = true;
- progresso = 0;
- textProgress = "Requisitando dados...";
- await _atualizarTalhoes();
- });
- Screen.keepOn(false);
- } catch (e) {
- _showDialog(context, e);
- }
- },
- ),
- FlatButton(
- child: Text("Não"),
- onPressed: () {
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- }
- );
- }
- },
- ),
- ],
- ),
- )
- ],
- ),
- body: FutureBuilder(
- future: tempList,
- builder: (context, snapshot) {
- switch(snapshot.connectionState) {
- case ConnectionState.none:
- case ConnectionState.waiting:
- return Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- 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,
- ),
- Text(textProgress, style: TextStyle(fontSize: 15.0, color: Colors.black),),
- ],
- )
- )
- ],
- );
- break;
- default:
- if(_connectionStatus == "ConnectivityResult.none") {
- return Container(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- Icon(Icons.signal_wifi_off, size: 40.0, color: Colors.red,),
- Center(
- child: Text(
- "Dispositivo Off-line",
- style: TextStyle(fontSize: 20.0),
- ),
- ),
- ],
- ),
- );
- } else
- if(snapshot.hasData) {
- return Container(
- padding: EdgeInsets.only(top: 10.0),
- child: Column(
- children: <Widget>[
- Center(
- child: Text(_dataRefresh),
- ),
- ],
- ),
- );
- } else if(snapshot.hasError) {
- _isRefreshing = false;
- Screen.keepOn(false);
- 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),
- ),
- ),
- Center(
- child: Text(snapshot.error.toString()),
- ),
- ],
- ),
- );
- } else {
- _isRefreshing = false;
- return Container();
- }
- break;
- }
- }
- ),
- ),
- Scaffold(
- backgroundColor: Colors.white,
- body: pageListaProdutor,
- ),
- Scaffold(
- backgroundColor: Colors.white,
- drawer: DrawerPage(pageCtrl: _pageCtrl, qtdNot: _qtdNot,),
- appBar: AppBar(
- title: Text("Notificações"),
- centerTitle: true,
- ),
- body: pageNotificacoes,
- )
- ],
- ),
- onWillPop: () {
- Future(() => false);
- },
- );
- }
- Widget buildHomePage(BuildContext context) {
- return Container();
- }
- Future<List> _getListaFilial() async {
- FilialHelper filialHelper = FilialHelper();
- print('--> Atualizando Filiais');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Filial> lista = 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(
- url + "filial.php",
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != "" && retorno["status"] != null) {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaFilial = retorno['lista'];
- await filialHelper.deleteAll();
- for (Map itens in listaFilial) {
- Filial filialIns = await filialHelper.saveFilial(Filial.fromMap(itens));
- lista.add(filialIns);
- }
- }
- return lista;
- }
- Future<List> _getListaSafra() async {
- SafraHelper safraHelper = SafraHelper();
- print('--> Atualizando Safras');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Safra> lista = 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(
- url + "safra.php",
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != "" && retorno["status"] != null) {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaSafra = retorno['lista'];
- await safraHelper.deleteAll();
- for (Map itens in listaSafra) {
- Safra safraIns = await safraHelper.saveSafra(Safra.fromMap(itens));
- lista.add(safraIns);
- }
- }
- return lista;
- }
- Future<List> _getListaCultura() async {
- CulturaHelper culturaHelper = CulturaHelper();
- print('--> Atualizando Culturas');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Cultura> lista = 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(
- url + "cultura.php",
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != "" && retorno["status"] != null) {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaCultura = retorno['lista'];
- await culturaHelper.deleteAll();
- for (Map itens in listaCultura) {
- Cultura culturaIns = await culturaHelper.saveCultura(Cultura.fromMap(itens));
- lista.add(culturaIns);
- }
- }
- return lista;
- }
- Future<List> _getListaTipoTitulo() async {
- TipoTituloHelper tipoTituloHelper = TipoTituloHelper();
- print('--> Atualizando Tipos de Título');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<TipoTitulo> lista = List();
- List<TipoTitulo> tiposTitulo = 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(
- url + "tipoTitulo.php",
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != "" && retorno["status"] != null) {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaTipoTitulo = retorno['lista'];
- await tipoTituloHelper.deleteAll();
- for (Map itens in listaTipoTitulo) {
- TipoTitulo tipoTituloIns = TipoTitulo();
- tipoTituloIns = await tipoTituloHelper.saveTipoTitulo(TipoTitulo.fromMap(itens));
- tiposTitulo.add(tipoTituloIns);
- }
- }
- return tiposTitulo;
- }
- Future<List> _getListaNotificacoesTecnico() async {
- NotificacoesHelper notificacoesHelper = NotificacoesHelper();
- print('--> Atualizando Notificações do Técnico');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Notificacoes> lista = 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(
- url + "notificacoes.php",
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != "" && retorno["status"] != null) {
- _showDialog(context, "Erro ao processar a requisição.");
- } else {
- var listaNotificacoes = retorno['lista'];
- //await notificacoesHelper.deleteAll();
- if(listaNotificacoes != null) {
- for (Map itens in listaNotificacoes) {
- Notificacoes not = Notificacoes.fromMap(itens);
- Notificacoes notificacao = await notificacoesHelper.saveNotificacao(not);
- lista.add(notificacao);
- }
- }
- }
- return lista;
- }
- Future<List<Produtor>> _getListaProdutorLocal() async {
- List<Produtor> lista = List();
- lista = await prodHelper.getAll();
- return lista;
- }
- Future<List<Produtor>> _atualizarTalhoes() async {
- Screen.keepOn(true);
- try {
- print('--> Atualizando Talhões');
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Produtor> lista = List();
- List<Propriedade> propriedades = List();
- List listaTalhao;
- 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);
- listaTalhao = await talhaoHelper.getListaTalhaoParaAtualizar().catchError((error) {
- _showDialog(context, error.toString());
- });;
- if (listaTalhao.length > 0) {
- print('--> Existe talhão para atualizar');
- Map dados = {
- "user": usuario,
- "password": encrypted,
- "talhao": listaTalhao,
- "opeExe": "A"
- };
- String ldados = json.encode(dados);
- http.Response response = await http.post(
- url + 'produtor.php',
- body: ldados).catchError((error) {
- _showDialog(context, error);
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != null && retorno["status"] != "") {
- _showDialog(context, retorno["status"]);
- } else {
- var result = retorno["lista"];
- if(result != null) {
- var resultPropriedade = result["propriedade"];
- if(resultPropriedade["talhao"].toString().startsWith("[")) {
- for (Map m in resultPropriedade["talhao"]) {
- if (m["retorno"] != null) {
- Notificacoes not = Notificacoes();
- not.Descricao = m["retorno"];
- not.Data = formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]);
- not.Situacao = "Não Lida";
- print('--> Salvando notificação');
- notificacoesHelper.saveNotificacao(not).then((notificacao) {}).catchError((error) {
- _showDialog(context, error.toString());
- });
- }
- }
- } else {
- String retorno = resultPropriedade["talhao"]["retorno"];
- if(retorno != null) {
- Notificacoes not = Notificacoes();
- not.Descricao = retorno;
- not.Data = formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]);
- not.Situacao = "Não Lida";
- notificacoesHelper.saveNotificacao(not).then((notificacao) {}).catchError((error) {
- _showDialog(context, error.toString());
- });
- }
- }
- }
- _getListaSafra();
- _getListaCultura();
- _getListaFilial();
- _getListaTipoTitulo();
- _getListaNotificacoesTecnico();
- tempList = _getListaProdutor();
- _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy ]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss ]);
- _isRefreshing = false;
- prefs.setString("TextoAtualizacao", _dataRefresh);
- }
- } else {
- print('--> Não existe talhão para atualizar');
- setState(() {
- _getListaSafra();
- _getListaCultura();
- _getListaFilial();
- _getListaTipoTitulo();
- _getListaNotificacoesTecnico();
- tempList = _getListaProdutor();
- _dataRefresh = "Atualizado em " + formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy ]) + " às " + formatDate(DateTime.now(), [HH, ':', nn, ':', ss ]);
- _isRefreshing = false;
- prefs.setString("TextoAtualizacao", _dataRefresh);
- });
- Screen.keepOn(false);
- return lista;
- }
- } catch(e) {
- _showDialog(context, e);
- }
- Screen.keepOn(false);
- }
- Future<List<Produtor>> _getListaProdutor() async {
- Screen.isKeptOn.then((value) {
- if(!value) {
- Screen.keepOn(true);
- }
- });
- try {
- ProdutorHelper prodHelper = ProdutorHelper();
- PropriedadeHelper propriedadeHelper = PropriedadeHelper();
- TalhaoHelper talhaoHelper = TalhaoHelper();
- NotificacoesCoopHelper notProdutorHelper = NotificacoesCoopHelper();
- TitulosCRHelper titCRHelper = TitulosCRHelper();
- NotificacoesPropHelper notPropriedadeHelper = NotificacoesPropHelper();
- print('--> Atualizando dados');
- int totalRegistros = 0;
- Map<String, dynamic> myMap = Map();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- List<Produtor> lista = List();
- List<Propriedade> propriedades = List();
- //String listaTalhao;
- 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);
- //listaTalhao = await talhaoHelper.getListaTalhaoParaAtualizar();
- //print(listaTalhao.toString());
- Map dados = {
- "user": usuario,
- "password": encrypted,
- "talhao": "",
- "opeExe": ""
- };
- String ldados = json.encode(dados);
- http.Response response = await http.post(url + 'produtor.php', body: ldados)
- .catchError((error) {
- _showDialog(context, error);
- throw error;
- });
- Map<String, dynamic> retorno = json.decode(response.body);
- if (retorno["status"] != null && retorno["status"] != "") {
- _showDialog(context, retorno["status"]);
- } else {
- var listaProdutor = retorno['lista'];
- totalRegistros = retorno['qtdReg'];
- await notProdutorHelper.deleteAll();
- await notPropriedadeHelper.deleteAll();
- await talhaoHelper.deleteAll();
- await propriedadeHelper.deleteAll();
- await titCRHelper.deleteAll();
- await titCPHelper.deleteAll();
- await prodHelper.deleteAll();
- for (Map itens in listaProdutor) {
- Produtor prod = Produtor();
- if (itens["codigo"] != 0 && itens["codigo"] != null) {
- Produtor prod = Produtor.fromMap(itens);
- prodHelper.saveProdutor(prod).then((prodInsert) {
- prod = prodInsert;
- print('--> Atualizando Produtor ${prod.id}');
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- });
- lista.add(prod);
- if(itens['notificacoesProdutor'].toString().startsWith("[")) {
- var listaNotificacoes = itens['notificacoesProdutor'];
- if(listaNotificacoes != null) {
- for (Map m in listaNotificacoes) {
- NotificacoesCoop notificacao = await notProdutorHelper.saveNotificacaoCoop(NotificacoesCoop.fromMap(m));
- print('--> Atualizando Notificações do Produtor ${notificacao.codProdutor}');
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- if(itens['notificacoesProdutor'] != null) {
- var notProd = NotificacoesCoop.fromMap(itens['notificacoesProdutor']);
- await notProdutorHelper.saveNotificacaoCoop(notProd);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- var listaPropriedades = itens['propriedade'];
- var listaTitulosCR = itens['titulosCR'];
- print('--> Atualizando Títulos a Receber');
- if (itens['titulosCR'].toString().startsWith("[")) {
- //É uma lista
- var titulosCR = itens['titulosCR'];
- if(titulosCR != null) {
- for (Map titCR in titulosCR) {
- TitulosCR tituloCR = await titCRHelper.saveTituloCR(TitulosCR.fromMap(titCR));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- //É um objeto
- if (itens['titulosCR'] != null) {
- var titulosCR = TitulosCR.fromMap(itens['titulosCR']);
- TitulosCR titCR = await titCRHelper.saveTituloCR(titulosCR);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- print('--> Atualizando Títulos a Pagar');
- if (itens['titulosCP'].toString().startsWith("[")) {
- //É uma lista
- var titulosCP = itens['titulosCP'];
- if(titulosCP != null) {
- for (Map titCP in titulosCP) {
- TitulosCP tituloCP = await titCPHelper.saveTituloCP(TitulosCP.fromMap(titCP));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- //É um objeto
- if (itens['titulosCP'] != null) {
- var titulosCP = TitulosCP.fromMap(itens['titulosCP']);
- TitulosCP titCR = await titCPHelper.saveTituloCP(titulosCP);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- print('--> Atualizando Propriedades');
- if (itens['propriedade'].toString().startsWith("[")) {
- //É uma lista
- var listaProp = itens['propriedade'];
- if(listaProp != null) {
- for (Map prop in listaProp) {
- Propriedade propi = await propriedadeHelper.savePropriedade(Propriedade.fromMap(prop));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- print('--> Atualizando Notificações da Propriedade');
- if(prop['notificacoesPropriedade'].toString().startsWith("[")) {
- var listaNotificacoes = prop['notificacoesPropriedade'];
- if(listaNotificacoes != null) {
- for (Map m in listaNotificacoes) {
- NotificacoesProp notificacao = await notPropriedadeHelper.saveNotificacaoProp(NotificacoesProp.fromMap(m));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- if(prop['notificacoesPropriedade'] != null) {
- var notProp = NotificacoesProp.fromMap(prop['notificacoesPropriedade']);
- await notPropriedadeHelper.saveNotificacaoProp(notProp);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- if (prop['talhao'].toString().startsWith('[')) {
- //Lista de Talhões
- if(prop['talhao'] != null) {
- for (Map talhao in prop['talhao']) {
- if (talhao != null) {
- Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
- }
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- //Objeto Talhão
- if (prop['talhao'] != null) {
- Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(prop['talhao']));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- }
- }
- } else {
- //É um objeto
- if (itens['propriedade'] != null) {
- var propriedades = Propriedade.fromMap(itens['propriedade']);
- //var talhao = Talhao.fromMap(listaPropriedades['talhao']);
- Propriedade prop = await propriedadeHelper.savePropriedade(propriedades);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- print('--> Atualizando Notificações da Propriedade');
- if(itens['propriedade']['notificacoesPropriedade'].toString().startsWith("[")) {
- var listaNotificacoes = itens['propriedade']['notificacoesPropriedade'];
- if(listaNotificacoes != null) {
- for (Map m in listaNotificacoes) {
- NotificacoesProp notificacao = await notPropriedadeHelper.saveNotificacaoProp(NotificacoesProp.fromMap(m));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- if(itens['propriedade']['notificacoesPropriedade'] != null) {
- var notProp = NotificacoesProp.fromMap(itens['propriedade']['notificacoesPropriedade']);
- await notPropriedadeHelper.saveNotificacaoProp(notProp);
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- print('--> Atualizando Talhões produtor: ${propriedades.idProdutor}');
- if (itens['propriedade']['talhao'].toString().startsWith('[')) {
- //Lista de Talhões
- if(itens['propriedade']['talhao'] != null) {
- for (Map talhao in itens['propriedade']['talhao']) {
- if (talhao != null) {
- Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(talhao));
- }
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- } else {
- //Objeto Talhão
- if (itens['propriedade']['talhao'] != null) {
- Talhao tal = await talhaoHelper.saveTalhao(Talhao.fromMap(itens['propriedade']['talhao']));
- setState(() {
- progresso = progresso + 1;
- textProgress = "Atualizando $progresso de $totalRegistros registros";
- });
- }
- }
- }
- }
- }
- }
- }
- /*getCountNotProp();
- getCountNotTec();
- getCountTitCP();
- getCountTitCR();
- getCountNotProd();
- getCountTalhao();
- getCountProdutor();
- getCountPropriedade();*/
- setState(() {
- _isRefreshing = false;
- _refresh = false;
- progresso = 0;
- _dataRefresh = "Atualizado em " + formatDate(
- DateTime.now(), [dd, '/', mm, '/', yyyy]) + " às " +
- formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
- });
- Screen.keepOn(false);
- return lista;
- } catch(e) {
- _showDialog(context, e);
- }
- }
- Future<Null> initConnectivity() async {
- String connectionStatus;
- // Platform messages may fail, so we use a try/catch PlatformException.
- try {
- connectionStatus = (await _connectivity.checkConnectivity()).toString();
- } catch (e) {
- print(e.toString());
- connectionStatus = 'Failed to get connectivity.';
- }
- // If the widget was removed from the tree while the asynchronous platform
- // message was in flight, we want to discard the reply rather than calling
- // setState to update our non-existent appearance.
- if (!mounted) {
- return;
- }
- setState(() {
- _connectionStatus = connectionStatus;
- });
- }
- void getCountNotProp() {
- notPropriedadeHelper.getCount().then((value) {
- print('Not. Propriedade: ' + value.toString());
- });
- }
- void getCountNotTec() {
- notificacoesHelper.getCount().then((value) {
- print('Not. Tecnico: ' + value.toString());
- });
- }
- void getCountTitCP() {
- titCPHelper.getCount().then((value) {
- print('Titulos CP: ' + value.toString());
- });
- }
- void getCountTitCR() {
- titCRHelper.getCount().then((value) {
- print('Titulos CR: ' + value.toString());
- });
- }
- void getCountNotProd() {
- notProdutorHelper.getCount().then((value) {
- print('Not. Produtor: ' + value.toString());
- });
- }
- void getCountCultura() {
- culturaHelper.getCount().then((value) {
- print('Culturas: ' + value.toString());
- });
- }
- void getCountSafra() {
- safraHelper.getCount().then((value) {
- print('Safras: ' + value.toString());
- });
- }
- void getCountProdutor() {
- prodHelper.getCount().then((value) {
- print('Produtores: ' + value.toString());
- });
- }
- void getCountFilial() {
- filialHelper.getCount().then((value) {
- print('Filiais: ' + value.toString());
- });
- }
- void getCountTipoTitulo() {
- tipoTituloHelper.getCount().then((value) {
- print('Tipos de Título: ' + value.toString());
- });
- }
- void getCountPropriedade() {
- propriedadeHelper.getCount().then((value) {
- print('Propriedades: ' + value.toString());
- });
- }
- void _showDialog(BuildContext context, String texto) {
- // flutter defined function
- showDialog(
- barrierDismissible: false,
- context: context,
- builder: (BuildContext context) {
- // return object of type Dialog
- return CustomAlertDialog(
- 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
Advertisement