Problem updating a list after inserting a data from another page

Asked

Viewed 317 times

1

I have a page that has a list of the names of "students" registered in a given course. Then, I click on a button to add. This button leads to a screen with all the names of the "students". The intention is to click on a name and then close this screen and update the list from the first screen. However, I’m not getting it.

How can I fix this?

My structure

  1. Listar Aluno: This page has a button that gives a Navigator.push to Addiralunoscreen by passing the id of the group in which the list belongs;
  2. Addiralunoscreen: Her body has the consultation page ConsultarAluno(Ela recebe o id também).

The page consult student has the following FutureBuild:

return FutureBuilder<QuerySnapshot>(
  future: Firestore.instance.collection("alunos").getDocuments(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
      var divideTiles = ListTile.divideTiles(
          tiles: snapshot.data.documents.map((doc) {
            return AlunosTile(doc,widget.id);
          }).toList(),
          color: Colors.grey[500])
          .toList();

      return ListView(
        children: divideTiles,
      );
    }
  }

That one FutureBuild builds the list of all registered students, and when I select a student he records in the bank the name of this student and goes back to the previous screen where have only students enrolled in that group. But this update in the database occurs, but on the screen nothing changes. To load the list I need to go back to a screen and see all the details of the group, and click on the student list button again, so the document updates.

What I was trying to do is when I click on the student and add him to the group, the screen that shows registered students updating with the student I selected on the next screen.

Follow the codes :

class _ListarAlunosState extends State<ListarAlunos> {


@override 

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Lista"),  

actions: <Widget>[
  

IconButton(
          icon: Icon(Icons.group_add),
          onPressed: () async {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        AdicionarAlunoScreen(widget.snapshot.documentID)));

          }),
    ],

  ),
  body: FutureBuilder<QuerySnapshot>(
      future: Firestore.instance
          .collection("trabalhos")
          .document(widget.snapshot.documentID)
          .collection("alunos")
          .getDocuments(),
      builder: (context, snapshotAluno) {
        if (!snapshotAluno.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        } else {
          return ListView.builder(
              shrinkWrap: true,
              itemCount: snapshotAluno.data.documents.length,
              itemBuilder: (BuildContext context, int index) {
                DocumentSnapshot doc = snapshotAluno.data.documents[index];
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    IconButton(
                      icon: Icon(Icons.perm_identity),
                      onPressed: () {},
                    ),
                    Text(
                      doc.data["nome"],
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize: 18.0, fontWeight: FontWeight.bold),
                    ),
                    IconButton(
                      icon: Icon(Icons.delete_forever),
                      onPressed: () {},
                    )
                  ],
                );
              });
        }
      }),
);
  }
}


class AdicionarAlunoScreen extends StatelessWidget {  

String id;



AdicionarAlunoScreen(this.id); 

 @override  

Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
    title: Text("Adicionar Aluno"),
),
body: ConsultaAlunos(id),
);


 }
}



class ConsultaAlunos extends StatelessWidget {



String nome;


ConsultaAlunos(this.nome);


@override


Widget build(BuildContext context) {
return FutureBuilder<QuerySnapshot>(
  future: Firestore.instance.collection("alunos").getDocuments(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return Center(
        child: CircularProgressIndicator(),
      );
    } else {
      var divideTiles = ListTile.divideTiles(
          tiles: snapshot.data.documents.map((doc) {
            return AlunosTile(doc,nome);
          }).toList(),
          color: Colors.grey[500])
          .toList();

      return ListView(
        children: divideTiles,
      );
    }
  },
);


 }
}

class AlunosTile extends StatefulWidget {
final DocumentSnapshot snapshot;
String id;
AlunosTile(this.snapshot,this.id);
@override
_AlunosTileState createState() => _AlunosTileState();
}
class _AlunosTileState extends State<AlunosTile> {
@override
Widget build(BuildContext context) {
return ListTile(
  title: Text(widget.snapshot.data["nome"],
    style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
  ),
leading: Icon(Icons.person_add),
  onTap: (){
    print(widget.snapshot.documentID);
    Firestore.instance.collection("trabalhos").document(widget.id).collection("alunos").add({
      "nome" : widget.snapshot.data["nome"]});
  },
   );
  }
}

  • If the answer was helpful, vote and mark as resposta aceita.

1 answer

1


Exchange the FutureBuilder used by a StreamBuilder

Before

FutureBuilder<QuerySnapshot>(
  future: Firestore.instance
      .collection("trabalhos")
      .document(widget.snapshot.documentID)
      .collection("alunos")
      .getDocuments(),
  builder: (context, snapshotAluno) {
    // Seu código
  }
)

Afterward

StreamBuilder(
  stream: Firestore.instance
    .collection("trabalhos")
    .document(widget.snapshot.documentID)
    .collection("alunos").snapshots(),
  builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
    // Seu código
  }
)

Doing so the list will update automatically when there is any change in your Firestore base.

Explanation

Roughly speaking... The StreamBuilder is "listening" to the changes that occur in your Firestore bank, so every time something changes there, the StreamBuilder will receive a new snapshot with updated data and so your list is automatically updated!

So if you make the change I suggested, after you enter the student’s name in the group being "heard" by StreamBuilder, the list will be updated alone, you don’t need to do anything else.

  • Thank you , it worked now I understood the reason Vlw

Browser other questions tagged

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