I am unable to list the data that I have saved in the database

I have a judgment model that has an element. When I add this element to the database fireBase, it gets added successfully. However, when I try to list the added elements, it doesn’t work. I add a judgment using an alertDialog, and then this judgment is added to the Firebase database and should be listed.



class Jugement {
  final String idJugement;
  final String matriculation;
  
  Jugement({required this.matriculation, required this.idJugement,/*required this.sanctions*/});

  Map<String, dynamic> toJson(Jugement instance) => <String, dynamic>{
    'matriculation': matriculation,
    'idJugement': idJugement,
  };

  factory Jugement.fromJson(Map<String, dynamic> json) => Jugement(
    matriculation: json['matriculation'],
    idJugement: json['idJugement'],
  );
}



//method for add in fireBase

Future<String> addJugement({
    required String matriculation,
  }) async {
    String res = "Some error occured";
    try {
      Jugement juge = Jugement(
          matriculation: matriculation,
        idJugement: const Uuid().v4(),
      );

      final res = await _firestore.
      collection('jugement').
      doc().
      set(
          juge.toJson(juge),
      );

    } catch (e) {
      //rethrow;
      log("erreur survenue", error: e);
    }
    return res;
  }


//My AlertDialog

import 'package:flutter/material.dart';

import '../../../core/service/authentification_service.dart';
import '../../../widgets/text_place.dart';

class AddJugementDialog extends StatefulWidget {
  @override
  _AddJugementDialogState createState() => _AddJugementDialogState();
}

class _AddJugementDialogState extends State<AddJugementDialog> {
  late TextEditingController matriculationController;
@override
  void initState() {
    matriculationController = TextEditingController();
    super.initState();
  }

  void addJugement() async {
    try{
      String res = await AuthentificationService().addJugement(
        matriculation: matriculationController.text, 
      );
      if (context.mounted) {
        Navigator.of(context).pop();
      }
  }catch(error) {
     print("erreur mec");
    }
  }

  @override
  Widget build(BuildContext context) {
    //Sanction? selectedSanction;

    return AlertDialog(
      title: const Padding(
        padding: EdgeInsets.only(left: 22.0, top: 15.0),
        child: Text('veuillez saisir le motif pour lequel le véhicule a été arrété', style: TextStyle(
          fontSize: 18.0,
          fontWeight: FontWeight.bold,
        ),),
      ),
      insetPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 40),
      contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      content: Column(
        children: [
          Expanded(
            child: Center(
              child: TextPlace(
                controller: matriculationController,
                obscureText: false,
                labelText: "add judgment",
                textInputType:
                TextInputType.text,
              ),
            ),
          ),

],
      ),


      actions: [
        TextButton(
          child: const Text('Annuler'),
          onPressed: () => Navigator.of(context).pop(),
        ),
        ElevatedButton(
          child: const Text('Ajouter'),
          onPressed: () {
            addJugement();
          },
        ),
      ],
    );
  }
}

//and my ListView page


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import '../../../core/modele/jugement/Jugement.dart';
import 'add_jugement.dart';

class JugementPage extends StatelessWidget {


  //I think the error is probably in this method
  Stream<List<Jugement>> readJudge() {
    try {
      final res = FirebaseFirestore.instance
          .collection('jugement')
          .snapshots()
          .map((snapshot) => snapshot.docs
              .map((duc) => Jugement.fromJson(duc.data()))
              .toList());
      return res;
    } catch (e) {
      print(e.toString());
      rethrow;
    }
  }

  Widget buildJudge(Jugement jugement) => ListTile(
        title: Text(jugement.matriculation),
        //subtitle: Text(jugement.sanctions as String),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Liste des jugements'),
      ),
      body: StreamBuilder<List<Jugement>>(
        stream: readJudge(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            final errorMessage = snapshot.error;
            return Center(
                child: Text(errorMessage.toString()),
            );
          } else if (snapshot.hasData) {
            final juge = snapshot.data!;
            return ListView(
              children: juge.map(buildJudge).toList(),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => AddJugementDialog(),
          );
        },
      ),
    );
  }
}





just try catch for see error

  • If JudgementPage is where you want things to get updated, you have a problem since it is a stateless widget. It needs to hold on to some state so when you update that state, the screen will get re-rendered. You need to have logic to update the JudgementPage when a judgment is added.

    – 

Leave a Comment