Field recording as Null in Firestore Flutter

Asked

Viewed 81 times

0

I’m trying to record a document inside another document (nested Documents) in Flutter with Firestore. The model is a property that has some fields, and next to the fields a collection of comforts, which in turn have only one id (imovelId) and description (description).

I managed to record the Real Estate, however when I try to record a commode in the collection of commodes inside a property, the description of the comfort always stays "null".

The structure looks like this:

[Imóvel]
    |-> imovelId: 'id do imovel'
    |-> endereco: 'endereco do imovel'
    |-> data:     'data da vistoria'
    |
    |->[Comodos]
           |
           |-> comodoId: 'valor do id deste comodo'
           |-> descricao: 'ex. Quarto'

Can someone help me understand what I’m doing wrong?

immovable model:

class Imovel {
  String imovelId;
  String endereco;
  String data;

  List<dynamic> comodos = [];

  Imovel(
      {this.imovelId, this.endereco, this.data, this.luz, this.agua, this.gas});

  Imovel.fromMap(Map<String, dynamic> json) {
    imovelId = json['imovelId'];
    endereco = json['endereco'];
    data = json['data'];

  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['imovelId'] = this.imovelId;
    data['endereco'] = this.endereco;
    data['data'] = this.data;
    data['comodos'] = this.comodos;
    return data;
  }
}

class Comodo {
  String comodoId;
  String descricao;

  Comodo({this.comodoId, this.descricao});

  Comodo.fromMap(Map<String, dynamic> json) {
    comodoId = json['comodoId'];
    descricao = json['descricao'];
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['comodoId'] = this.comodoId;
    data['descricao'] = this.descricao;
    return data;
  }
}

Provider:

class ImovelProvider with ChangeNotifier {
  var firestoreService = FirestoreService();
  String _imovelId;
  String _endereco;
  String _data;

  String _comodoId;
  String _descricao;
  var uuid = Uuid();

  // Getters
  String get imovelId => _imovelId;
  String get endereco => _endereco;
  String get data => _data;
  String get comodoId => _comodoId;
  String get descricao => _descricao;


  carregarValoresComodo(Comodo comodo) {
    _comodoId = comodo.comodoId;
    _descricao = comodo.descricao;
    notifyListeners();
  }

  salvarComodo() {
    if (_comodoId == null) {
      var novoComodo = Comodo(comodoId: Uuid().v4(), descricao: descricao);
      firestoreService.salvarComodo(novoComodo, Imovel(imovelId: imovelId));
      notifyListeners();
    } else {
      var comodoExistente = Comodo(
        comodoId: _comodoId,
        descricao: _descricao,
      );
      firestoreService.salvarComodo(
          comodoExistente, Imovel(imovelId: _imovelId));
      notifyListeners();
    }
  }

Service:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:jc_vistoria/models/imovel.dart';

class FirestoreService {
  FirebaseFirestore _db = FirebaseFirestore.instance;



  Future<void> salvarComodo(Comodo comodo, Imovel imovel) {
    return _db
        .collection("imoveis")
        .doc(imovel.imovelId)
        .collection('comodos')
        .doc(comodo.comodoId)
        .set(comodo.toMap());
  }

}

Screen edit_comodo.Dart:

 class EditComodo extends StatefulWidget {
  final Comodo comodo;
  final Imovel imovel;

  EditComodo([this.comodo, this.imovel]);

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

class _EditComodoState extends State<EditComodo> {
  final descricaoController = TextEditingController();

  @override
  void dispose() {
    descricaoController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    if (widget.comodo == null) {
      //Novo imovel
      descricaoController.text = "";

      new Future.delayed(Duration.zero, () {
        final imovelProvider =
            Provider.of<ImovelProvider>(context, listen: false);
        imovelProvider.carregarValoresComodo(Comodo());
      });
    } else {
      //Imovel existente
      descricaoController.text = widget.comodo.descricao;

      // atualiza os estados
      new Future.delayed(Duration.zero, () {
        final imovelProvider =
            Provider.of<ImovelProvider>(context, listen: false);
        imovelProvider.carregarValoresComodo(widget.comodo);
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final imovelProvider = Provider.of<ImovelProvider>(context);

    return Scaffold(
      appBar: AppBar(title: Text('Adicionar/Editar comodos')),
      body: Padding(
        padding: const EdgeInsets.all(28.0),
        child: ListView(children: <Widget>[
          Text(
            'Descrição:',
            textAlign: TextAlign.left,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          TextFormField(
            decoration:
                InputDecoration(hintText: "Digite a descrição deste comodo..."),
            keyboardType: TextInputType.text,
            controller: descricaoController,
          ),
          SizedBox(height: 20),
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            RaisedButton(
              color: Colors.green,
              textColor: Colors.white,
              onPressed: () {
                imovelProvider.salvarComodo();
                Navigator.of(context).pop();
              },
              child: Icon(Icons.save),
            ),
            SizedBox(width: 10),
            RaisedButton(
              color: Colors.yellow,
              textColor: Colors.black,
              onPressed: () {},
              child: Icon(Icons.border_top),
            ),
            SizedBox(width: 10),
            RaisedButton(
              color: Colors.red,
              textColor: Colors.white,
              onPressed: () {
                imovelProvider.removerComodo(widget.comodo, widget.imovel);
                Navigator.of(context).pop();
              },
              child: Icon(Icons.delete_forever),
            )
          ])
        ]),
      ),
    );
  }
}

inserir a descrição da imagem aqui

  • 1
  • Thank you Costamilam, I’ve edited and removed the parts I believe are unnecessary.

  • 1

    In the salvarComodo of its President, in if the description comes from the variable descricao, already in the else comes from _descricao, a two two is not wrong? Debug the code and check if in the service comodo.descricao is not null, if yes is receiving wrong, then check the code that calls it, doing the same process until you find the source of the problem

  • Unfortunately not, Costamilam. I’ve tried _Description, and also Description. Every time Description is saved as null.

  • For the object Immovel, this variable naming system is working normal @Costamilam

1 answer

0

I found the fault. Needed to define the function in Textformfield:

onChanged: (value) {
            imovelProvider.mudarDescricao(value);
          }),

Browser other questions tagged

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