CRUD in flutter

Asked

Viewed 615 times

0

I have a doubt, I know what the problem is but I have no idea how to solve. In a crud I have a parameter idade which is int (defined as INTEGER in the bank) and I can not register in the bank but if I insert manually, everything is OK and when I edit only the age does not edit or she edits all (I do not know for sure). Already delete and list are OK.

Registration screen:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:giphysearch/models/clienteModel.dart';
import 'package:giphysearch/pages/tarefa7cadastro.dart';
import 'package:scoped_model/scoped_model.dart';

  final _nomeController = TextEditingController();
  final _idadeController = TextEditingController();
  final _emailController = TextEditingController();

  num _numIdade = num.tryParse(_idadeController.text);  
  int intTryParse = int.tryParse(_idadeController.text);
class Cadastro extends StatefulWidget {

  final Cliente cliente;

  Cadastro({this.cliente});

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

class _CadastroState extends State<Cadastro> {

  final _nameFocus = FocusNode();

  bool _userEdited = false;

  Cliente _editedCliente;
  ClienteHelper helper = ClienteHelper();

//Etse acusa o erro
//Aqui eu uso para testar a inserção no banco
 /*
 @override
 void initState(){
    super.initState();
   Cliente c = Cliente();
    c.nome = "nome";
    c.idade = 20;
    c.email = "email";
    helper.inserirCliente(c);

     /* helper.getAllClientes().then((list){
     print(list);
  });*/

 }*/


//Este é como se não reconhecesse 
  @override
  void initState() {
    super.initState();

    if(widget.cliente == null){
      _editedCliente = Cliente();
    } else {
      _editedCliente = Cliente.fromMap(widget.cliente.toMap());

      _nomeController.text = _editedCliente.nome;
      _numIdade = _editedCliente.idade;
      _emailController.text = _editedCliente.email;
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _requestPop,
      child:  ScopedModel<ClienteHelper>(
        model: ClienteHelper(),
        child: Scaffold(
      appBar: AppBar(
        title: Text("CRUD"),
        backgroundColor: Colors.deepPurpleAccent,
        centerTitle: true,
      ),

        floatingActionButton: FloatingActionButton(
          onPressed: (){
            if(_editedCliente.nome != null && _editedCliente.nome.isNotEmpty){
              Navigator.pop(context, _editedCliente);
            } else {
              FocusScope.of(context).requestFocus(_nameFocus);
            }
          },
          child: Icon(Icons.save),
          backgroundColor: Colors.red,
        ),

        body: ScopedModelDescendant<ClienteHelper>(
          builder: (context, child, model){
            return  SingleChildScrollView(
          padding: EdgeInsets.all(10.0),
          child: Column(
            children: <Widget>[
              TextField(
                controller: _nomeController,
                focusNode: _nameFocus,
                decoration: InputDecoration(labelText: "Nome"),
                onChanged: (text){
                  _userEdited = true;
                  setState(() {
                    _editedCliente.nome = text;
                  });
                },
              ),
              TextField(
                controller: _idadeController,
                decoration: InputDecoration(labelText: "Idade"),
                onChanged: (text){
                  _userEdited = true;
                  _editedCliente.idade = _numIdade;
                },
                keyboardType: TextInputType.number,
              ),
              TextField(
                controller: _emailController,
                decoration: InputDecoration(labelText: "Email"),
                onChanged: (text){
                  _userEdited = true;
                  _editedCliente.email = text;
                },
                keyboardType: TextInputType.emailAddress,
              ),
            ],
          ),
        );
          }
          )
        )


      ),
    );
  }

  Future<bool> _requestPop(){
    if(_userEdited){
      showDialog(context: context,
        builder: (context){
          return AlertDialog(
            title: Text("Descartar Alterações?"),
            content: Text("Se sair as alterações serão perdidas."),
            actions: <Widget>[
              FlatButton(
                child: Text("Cancelar"),
                onPressed: (){
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                child: Text("Sim"),
                onPressed: (){
                  Navigator.pop(context);
                  Navigator.pop(context);
                },
              ),
            ],
          );
        }
      );
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }

}

Save customer in bank:

//Salvando o Cliente noo banco
  Future<Cliente> inserirCliente(Cliente cliente)async{
    Database dbCliente = await db;
    cliente.id = await dbCliente.insert(clienteTable, cliente.toMap());
    return cliente;
  }

Update in the bank:

  //Atualizar os dados do cliente
  Future<int>updateCliente(Cliente cliente)async{
    Database dbCliente = await db;
    return await dbCliente.update(clienteTable, cliente.toMap(), where: "$idColumn = ?", whereArgs: [cliente.id]);
  }

I believe the error is on the screen Cadastro (which is the same for the update) but I can’t find this error.

  • Is there an error trying to register a new customer? Or it just doesn’t save age?

1 answer

1

Regarding the age update your error is time to set the entered value to _editedClient.age, try changing the age Textfield for this:

  TextField(
    controller: _idadeController,
    decoration: InputDecoration(labelText: "Idade"),
    onChanged: (text){
      _userEdited = true;
      _editedCliente.idade = text; // se a variável idade for int use int.parse(text)
    },
    keyboardType: TextInputType.number,
  ),

in the matter of saving or updating table data, try using transaction function, I particularly use it and have no problems. Try that code, I didn’t test it because I’m at work and I did it on the Otepad:

Future<Cliente> inserirCliente(Cliente cliente)async{
    Database dbCliente = await db;
    cliente.id = await dbCliente.transaction((txn) async {
        return await txn.rawInsert("INSERT INTO $clienteTable($NOME, $IDADE) VALUES('${cliente.nome}', '${cliente.idade}')");
    });
    return cliente;
  }

To update you can use the same idea only by changing rawInsert to rawUpdate and changing the conditions for the update.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.