Pessoal estou montando um tela que lista as informações da Api em um CheckboxListTile até ai beleza, porém estou com um problema ao marcar um checkbox e rolar a barra de rolagem para baixo e subir o checkbox marcado volta a ficar desmarcado. Estou apanhando nesse problema, segue o código abaixo:
//Código da View
import 'package:delayed_display/delayed_display.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/Classes/CheckboxPedidos.dart';
import 'package:flutter_app/Classes/Pedidos.dart';
import 'package:flutter_app/Classes/Status.dart';
import 'package:flutter_app/Home.dart';
import 'package:flutter_app/LoginPage.dart';
import 'package:flutter_app/telasAG/Palete.dart';
import 'package:flutter_app/telasAG/conexao/ApiPedido.dart';
import 'package:flutter_app/telasAG/controllers/PedidoController.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/animation.dart';
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:toast/toast.dart';
import 'package:get/get.dart';
class ListaPedidos extends StatefulWidget {
String cnpj;
String nome;
String cpf;
String empresa;
String email;
String nivel;
String param;
String pesquisa;
ListaPedidos(this.pesquisa, {this.cnpj, this.nome, this.cpf, this.empresa, this.email, this.nivel, this.param} );
@override
_ListaPedidosState createState() => _ListaPedidosState();
}
class _ListaPedidosState extends State<ListaPedidos> with SingleTickerProviderStateMixin {
TextEditingController _controllerStatus = TextEditingController();
var _perfil;
Future<Pedidos> retornoDaApi;
List<bool> _flag = List();
bool _selectAll = false;
String nota, produto, lote, unidade;
AnimationController _controller;
Animation<double> _animation;
static const _TABELA = "pedidos";
Status _selected;
List<Status> status = <Status>[
const Status(0, 'NÃO'),
const Status(1, 'SIM'),
];
loadingLista(int qtd){
_flag = [];
for(int i = 0; i < qtd; i++){
_flag.add(false);
}
return _flag;
}
//Ativa ao inicializar
initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 10),
vsync: this,
);
_animation = Tween(
begin: 1.0,
end: 0.0,
).animate(_controller);
_selected=status[0];
_controller.forward();
}
@override
dispose() {
_controller.dispose();
super.dispose();
}
_conexaoBancoDados() async {
final caminhoBancoDados = await getDatabasesPath();
final localBancoDados = join(caminhoBancoDados, "banco.db");
var banco = await openDatabase(
localBancoDados,
version: 1,
onCreate: (db, dbVersaoAtual){
//db.execute("DROP TABLE IF EXISTS pedidos");
String sql = "CREATE TABLE pedidos (id INTEGER PRIMARY KEY AUTOINCREMENT, nota_fiscal VARCHAR, lote_serial VARCHAR, produto VARCHAR, qtd_disp VARCHAR, lote VARCHAR, unidade VARCHAR, cnpj VARCHAR, palete VARCHAR, qtd_total VARCHAR, qtd_uz VARCHAR, cubagem VARCHAR) ";
db.execute(sql);
}
);
//print("aberto: "+ banco.isOpen.toString());
return banco;
}
_recuperar(BuildContext context, String status, String empresa) async {
Database db = await _conexaoBancoDados();
String sql = "SELECT * FROM ${_TABELA}";
List pedidos = await db.rawQuery(sql);
print(pedidos.toString());
if(pedidos.length > 0){
for(var pedido in pedidos){
print(
"item id: "+ pedido['id'].toString() +
" nota_fiscal: " + pedido['nota_fiscal'] +
" lote_serial: " + pedido['lote_serial'] +
" produto: " + pedido['produto'] +
" qtd_disp: " + pedido['qtd_disp'] +
" lote: " + pedido['lote'] +
" cnpj: " + pedido['cnpj'] +
" unidade: " + pedido['unidade'] +
" cubagem: " + pedido['cubagem'] +
" palete: " + pedido['palete'] +
" auth: " + status
);
// ApiPedido api = ApiPedido();
// api.cadastrarPedido(
// pedido['nota_fiscal'],
// pedido['lote_serial'],
// pedido['produto'],
// pedido['qtd_disp'],
// pedido['lote'],
// pedido['unidade'],
// pedido['cnpj'],
// pedido['cubagem'],
// pedido['palete'],
// status,
// empresa,
// context
// );
}
}else{
Toast.show(
"Nenhum pedido foi selecionado",
context,
duration: Toast.LENGTH_LONG,
backgroundColor: Colors.redAccent,
gravity: Toast.CENTER
);
}
}
_salvar(String nota, String produto, String lote, String qtd, String cubagem, String unidade, String uz, String serial, String cnpj, String qtd_total, qtd_uz, bool checked) async {
String valorSelecionado = nota+";"+produto+";"+lote+";"+qtd+";"+cubagem+";"+unidade+";"+uz+";"+serial+";"+qtd_total+";"+qtd_uz;
if(checked == true){
Database db = await _conexaoBancoDados();
Map<String, dynamic> dadosPedido = {
"nota_fiscal" : nota,
"lote_serial": serial,
"produto": produto,
"qtd_disp": qtd,
"lote": lote,
"unidade": unidade,
"cnpj": cnpj,
"palete": uz,
"qtd_total": qtd_total,
"qtd_uz": qtd_uz,
"cubagem": cubagem,
};
int id = await db.insert(_TABELA, dadosPedido);
print("Salvo1: $id");
}else{
}
}
_remover() async{
Database db = await _conexaoBancoDados();
db.delete(
_TABELA
);
}
@override
Widget build(BuildContext context) {
if(widget.nivel == '1'){
_perfil = "Cliente";
}else{
_perfil = "Transportadora";
}
//_conexaoBancoDados();
//_remover();
//_controller.forward();
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset(
"imagens/LOGO.jpg",
width: 100,
height: 100,
),
Text(
"Armazém Geral\n${widget.empresa}\nPerfil: ${_perfil}",
style: TextStyle(
color: Colors.black,
fontSize: 12
),
),
IconButton(
color: Colors.black87,
icon: Icon(Icons.logout),
onPressed: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => LoginPage()
)
);
},
)
],
),
backgroundColor: Colors.white,
),
body: Container(
padding: EdgeInsets.all(16),
child: FutureBuilder<List<dynamic>>(
future: ApiPedido.pesquisar(widget.pesquisa, widget.cnpj, context),
builder: (context, snapshot){
if(snapshot.hasError){
print(snapshot.error);
}
return snapshot.hasData ? Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Pedidos por Paletes",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold
),
),
SizedBox(
height: 10,
),
Text(
"* Marque o item que deseja reservar",
style: TextStyle(
fontSize: 13,
color: Colors.red
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:[
Text(
"Clique ao lado para selecionar tudo",
style: TextStyle(
fontSize: 12,
color: Colors.red
),
),
IconButton(
icon: Icon(Icons.save_alt),
iconSize: 50.0,
onPressed: (){
if(_flag.contains(false)){
setState(() {
_flag.add(true);
_selectAll = true;
});
}else{
setState(() {
_flag.add(false);
_selectAll = false;
});
}
}
),
]
),
SizedBox(
height: 10,
),
Expanded(
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index){
List<dynamic> list = snapshot.data;
PedidoController controller = PedidoController();
//print(snapshot.data);
for(int u = 0; u < snapshot.data.length; u++){
_flag.add(false);
}
print(_flag[index]);
//loadingLista(snapshot.data.length);
_selectAll == true ?
_salvar(
list[index]['nota_fiscal'],
list[index]['produto'],
list[index]['lote'],
list[index]['qtd_disp'],
list[index]['cubagem'],
list[index]['unid_medida'],
list[index]['palete'],
list[index]['lote_serial'],
list[index]['qtd_total'],
list[index]['qtd_uz'],
widget.cnpj,
_flag[index]
) : _remover();
return Column(
children: [
// GetX(
// builder: (_){
// ListTile(/
CheckboxPedidos(
nota: list[index]['nota_fiscal'],
produto: list[index]['produto'],
lote: list[index]['lote'],
qtd: list[index]['qtd_disp'],
unidade: list[index]['unid_medida'],
cnpjCli: widget.cnpj,
uz: list[index]['palete'],
checked: _flag[index],
serial: list[index]['lote_serial'],
cubagem: list[index]['cubagem'],
qtd_total: list[index]['qtd_total'],
qtd_uz: list[index]['qtd_uz'],
),
// ),
//},
//),
]
);
}
),
),
],
) :
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DelayedDisplay(
delay: Duration(seconds: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
Icons.warning,
color: Colors.orangeAccent,
),
Text(
"Dados não encontrados",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.black87,
),
),
],
),
),
SizedBox(
height: 20,
),
FadeTransition(
child: Column(
children: [
Text("Carregando...", style: TextStyle(fontSize: 15),),
SizedBox(
height: 10,
),
Center(child: CircularProgressIndicator())
],
),
opacity: _animation
)
],
);
},
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
floatingActionButton: FloatingActionButton(
elevation: 8,
backgroundColor: Colors.orange,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.home, color: Colors.white70),
Text("Inicio",
style: TextStyle(
fontSize: 10,
color: Colors.white70
),
)
],
),
onPressed: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Home(
cnpj: widget.cnpj,
nome: widget.nome,
cpf: widget.cpf,
empresa: widget.empresa,
email: widget.email,
nivel: widget.nivel,
)
)
);
},
),
bottomNavigationBar: BottomAppBar(
elevation: 8,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
width: 15,
),
RaisedButton(
child: SizedBox(
height: 68,
child: Row(
children: [
Icon(Icons.arrow_back, color: Colors.white70),
//Text("Voltar", style: TextStyle(color: Colors.white70))
],
),
),
color: Colors.orange,
shape: CircleBorder(),
onPressed: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Palete(
cnpj: widget.cnpj,
nome: widget.nome,
cpf: widget.cpf,
empresa: widget.empresa,
email: widget.email,
nivel: widget.nivel,
param: widget.param,
)
)
);
}
),
SizedBox(
width: 20,
),
RaisedButton(
elevation: 8,
child: SizedBox(
height: 55,
child: Row(
children: [
Text("Gerar Pedido", style: TextStyle(color: Colors.white70))
],
),
),
color: Colors.lightBlue,
onPressed: (){
showDialog(
context: context,
builder: (context){
return AlertDialog(
title: Text("Autoriza Remontagem?"),
content: DropdownButtonFormField<Status>(
icon: Icon(Icons.arrow_drop_down),
iconSize: 40,
isExpanded: true,
elevation: 16,
style: TextStyle(color: Colors.orangeAccent),
value: _selected,
onChanged: (Status newValue){
setState(() {
_selected = newValue;
});
},
items: status.map((Status status) {
return DropdownMenuItem<Status>(
value: status,
child: Text(status.status)
);
}).toList(),
),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text("Cancelar")
),
FlatButton(
onPressed: () {
_recuperar(context, _selected.id.toString(), widget.empresa);
Navigator.pop(context);
},
child: Text("Salvar")
),
],
);
}
);
}
),
],
),
)
);
}
}
//Codigo do Checkbox
import 'package:flutter/material.dart';
import 'package:flutter_app/Classes/Pedidos.dart';
import 'package:flutter_app/telasAG/ListaPedidos.dart';
import 'package:flutter_app/telasAG/controllers/PedidoController.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:get/state_manager.dart';
class CheckboxPedidos extends StatefulWidget {
CheckboxPedidos({ this.nota, this.produto, this.lote, this.qtd, this.cubagem, this.unidade, this.checked, this.cnpjCli, this.uz, this.serial, this.qtd_total, this.qtd_uz });
String nota, produto, lote, qtd, cubagem, unidade, uz, serial, qtd_total, qtd_uz;
String cnpjCli;
bool checked;
@override
_CheckboxPedidosState createState() => _CheckboxPedidosState();
}
class _CheckboxPedidosState extends State<CheckboxPedidos> {
static const _TABELA = "pedidos";
_conexaoBancoDados() async {
final caminhoBancoDados = await getDatabasesPath();
final localBancoDados = join(caminhoBancoDados, "banco.db");
var banco = await openDatabase(
localBancoDados,
version: 1,
onCreate: (db, dbVersaoAtual){
//db.execute("DROP TABLE IF EXISTS pedidos");
String sql = "CREATE TABLE pedidos (id INTEGER PRIMARY KEY AUTOINCREMENT, nota_fiscal VARCHAR, lote_serial VARCHAR, produto VARCHAR, qtd_disp VARCHAR, lote VARCHAR, unidade VARCHAR, cnpj VARCHAR, palete VARCHAR, qtd_total VARCHAR, qtd_uz VARCHAR, cubagem VARCHAR) ";
db.execute(sql);
}
);
//print("aberto2: "+ banco.isOpen.toString());
return banco;
}
_salvar(String nota, String produto, String lote, String qtd, String cubagem, String unidade, String uz, String serial, String cnpj, String qtd_total, qtd_uz, bool checked) async {
String valorSelecionado = nota+";"+produto+";"+lote+";"+qtd+";"+cubagem+";"+unidade+";"+uz+";"+serial;
if(checked == true){
Database db = await _conexaoBancoDados();
Map<String, dynamic> dadosPedido = {
"nota_fiscal" : nota,
"lote_serial": serial,
"produto": produto,
"qtd_disp": qtd,
"lote": lote,
"unidade": unidade,
"cnpj": cnpj,
"palete": uz,
"qtd_total": qtd_total,
"qtd_uz": qtd_uz,
"cubagem": cubagem
};
int id = await db.insert(_TABELA, dadosPedido);
print("Salvo2: $id");
}else{
_remover();
}
}
_remover() async{
Database db = await _conexaoBancoDados();
db.delete(
_TABELA
);
}
@override
Widget build(BuildContext context) {
List<Text> _listas = [
Text("Nota: "+widget.nota, style: TextStyle(fontSize: 13)),
Text("Produto: "+widget.produto, style: TextStyle(fontSize: 13)),
Text("Lote: "+widget.lote, style: TextStyle(fontSize: 13)),
Text("Medida: "+widget.unidade, style: TextStyle(fontSize: 13)),
Text("Cubagem: "+widget.cubagem, style: TextStyle(fontSize: 13)),
Text("Palete: "+widget.uz, style: TextStyle(fontSize: 13)),
Text("QTD: "+widget.qtd, style: TextStyle(fontSize: 13)),
];
PedidoController controller = PedidoController();
//Obx(() =>
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.teal),
borderRadius: BorderRadius.circular(13)
),
child: CheckboxListTile(
activeColor: Colors.teal,
selected: widget.checked,//controller.checked.value,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Nota: "+widget.nota, style: TextStyle(fontSize: 13)),
Text("Produto: "+widget.produto, style: TextStyle(fontSize: 13)),
Text("Lote: "+widget.lote, style: TextStyle(fontSize: 13)),
Text("Medida: "+widget.unidade, style: TextStyle(fontSize: 13)),
Text("Cubagem: "+widget.cubagem, style: TextStyle(fontSize: 13)),
Text("Palete: "+widget.uz, style: TextStyle(fontSize: 13)),
Text("QTD: "+widget.qtd, style: TextStyle(fontSize: 13)),
]
),
value: widget.checked, //controller.checked.value,
onChanged: (bool value){
//controller.checked.value = value;
setState(() {
widget.checked = value;
});
print(widget.checked);
//loadingLista(widget.qtdLista);
// _salvar(
// widget.nota,
// widget.produto,
// widget.lote,
// widget.qtd,
// widget.cubagem,
// widget.unidade,
// widget.uz,
// widget.serial,
// widget.cnpjCli,
// widget.qtd_total,
// widget.qtd_uz,
// widget.checked
// );
},
),
);
// );
}
}
//Código da Api
import 'package:flutter/material.dart';
import 'package:flutter_app/Classes/Pedidos.dart';
import 'package:flutter_app/telasAG/ListaCNPJ.dart';
import 'package:flutter_app/telasAG/VisualizarTransp.dart';
import 'package:http/http.dart' as http;
import 'package:sqflite/sqflite.dart';
import 'dart:convert';
import 'package:toast/toast.dart';
import 'package:path/path.dart';
class ApiPedido {
static const _TABELA = "pedidos";
static Future<List<dynamic>> pesquisar(String pesquisa, String cnpj, BuildContext context) async {
var url = 'http://localhost/camera/api.php';
final response = await http.get(
url + "?action=pesquisaPedido"
"&busca=$pesquisa"
"&cnpj=$cnpj"
);
if (response.statusCode == 200) {
return json.decode(response.body);
}else{
Toast.show(
"Falha de comunicação com Servidor",
context,
duration: Toast.LENGTH_LONG,
backgroundColor: Colors.redAccent,
gravity: Toast.CENTER
);
}
}
cadastrarPedido(String nota_fiscal, String lote_serial, String produto, String qtd_disp, String lote, String unidade, String cnpj, String cubagem, String palete, String auth, String empresa, BuildContext context ) async {
var url = 'http://localhost/camera/api.php';
final response = await http.get(
url + "?action=cadastrarPedido"
"¬a_fiscal=$nota_fiscal"
"&lote_serial=$lote_serial"
"&produto=$produto"
"&qtd_disp=$qtd_disp"
"&lote=$lote"
"&unidade=$unidade"
"&cnpj=$cnpj"
"&cubagem=$cubagem"
"&palete=$palete"
"&auth=$auth"
"&empresa=$empresa"
);
if (response.statusCode == 200) {
print("response: "+ response.body);
var mensagem;
if(response.body == '1'){
mensagem = "Cadastro com sucesso";
}else{
mensagem = "Erro ao cadastrar";
}
Toast.show(
mensagem,
context,
duration: Toast.LENGTH_LONG,
backgroundColor: response.body == '1' ? Colors.green : Colors.redAccent,
gravity: Toast.CENTER
);
conexaoBancoDados() async {
final caminhoBancoDados = await getDatabasesPath();
final localBancoDados = join(caminhoBancoDados, "banco.db");
var banco = await openDatabase(
localBancoDados,
version: 1,
onCreate: (db, dbVersaoAtual){
String sql = "CREATE TABLE pedidos (id INTEGER PRIMARY KEY AUTOINCREMENT, nota_fiscal VARCHAR, lote_serial VARCHAR, produto VARCHAR, qtd_disp VARCHAR, lote VARCHAR, unidade VARCHAR, cnpj VARCHAR, palete VARCHAR, cubagem VARCHAR) ";
db.execute(sql);
}
);
return banco;
}
remover() async{
Database db = await conexaoBancoDados();
db.delete(
_TABELA
);
}
if(response.body == '1'){
remover();
}
}else{
Toast.show(
"Falha de comunicação com Servidor",
context,
duration: Toast.LENGTH_LONG,
backgroundColor: Colors.redAccent,
gravity: Toast.CENTER
);
}
}
}