Laurent Thomas
Laurent Thomas

Reputation: 282

Flutter Firebase get recordID

In the code below, I am trying to get the id of snap. This info is supposed to be recorded, later if the user tap on save.

But, I am not able to get the right id associated with the project selected. If you can put me to the right direction, it would be appreciated. Many thanks.

Padding(
              padding: const EdgeInsets.fromLTRB(8.0, 3.0, 0.0, 0.0),
              child: StreamBuilder<QuerySnapshot>(
                  stream: FirebaseFirestore.instance
                      .collection('Users')
                      .doc(FirebaseAuth.instance.currentUser.uid)
                      .collection('projects')
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData)
                      const Text("Loading.....");
                    else {
                      List<DropdownMenuItem <Project>> goalItems = [];
                      for (int i = 0; i < snapshot.data.docs.length; i++) {
                         snap = snapshot.data.docs[i];

                       // print (gael.id);
                       // print(snap['project_Name']);
                        goalItems.add(
                          DropdownMenuItem(
                            value: Project(snap['project_Name'], snap.id),//(snap['project_Name'], snap.id),
                            child: SizedBox(
                              width:MediaQuery.of(context).size.width*0.89,
                              child: Text(
                                (snap['project_Name']),
                                style: TextStyle(color: Colors.black),
                              ),
                            ),
                            //  style: TextStyle(color: Color(0xff11b719)),
                            // ),

                          ),
                        );
                      }
                      return Row(
                          children:<Widget> [
                            DropdownButton <Project>(
                              items: goalItems,
                              onChanged: (Project pro) {
                                setState(() {
                                  selectedProject = pro.name;

                                  taskNewValue ['project_Name'] = pro.name ;
                                  taskNewValue['project_ID'] = pro.id;
                                  print(pro.id);
                                });
                              },
                              value: selectedProject,
                              isExpanded: false,
                              hint:  Text(projectName,
                                style: TextStyle(color: Color (0xff29B6F6)), //Color(0xff0d53dc)),
                              ),
                            )]);
                    }
                    return Container(
                      height: 0,width: 0,
                    );
                  }),
            ),
class Project {
 // var User(this.name, this.id);
  final String id;
  final String name;

  Project(this.id,this.name);
}

//Last modification done. When I remove value, it works, but, when I select a new item, it is not displayed

Padding(
              padding: const EdgeInsets.fromLTRB(8.0, 3.0, 0.0, 0.0),
              child: StreamBuilder<QuerySnapshot>(
                  stream: FirebaseFirestore.instance
                      .collection('Users')
                      .doc(FirebaseAuth.instance.currentUser.uid)
                      .collection('projects')
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData)
                      const Text("Loading.....");
                    else {
                      List<DropdownMenuItem <Project>> goalItems = [];
                      for (int i = 0; i < snapshot.data.docs.length; i++) {
                        snap = snapshot.data.docs[i];
                        print(snap.id);
                        print(snap['project_Name']);

                        goalItems.add(
                          DropdownMenuItem(
                            value: Project(snap.id, snap['project_Name']),
                            //(snap['project_Name'], snap.id),
                            child: SizedBox(
                              width: MediaQuery
                                  .of(context)
                                  .size
                                  .width * 0.89,
                              child: Text(
                                (snap['project_Name']),
                                style: TextStyle(color: Colors.black),
                              ),
                            ),
                            //  style: TextStyle(color: Color(0xff11b719)),
                            // ),

                          ),
                        );
                      }
                      return Row(
                          children: <Widget>[
                            DropdownButton <Project>(
                              items: goalItems,
                              onChanged: (Project pro) {
                                setState(() {
                                  selectedProject = pro.name;
                                  project_ID=pro.id;
                                  myTest = pro.name;
                                  final test4 = Project(project_ID,  myTest);
                                //  print('ID');
                                //  print(pro.id);
                                //  print('name');
                                //  print(pro.name);
                                //  print('test4');
                                //  print(test4.id);
                                //  print(test4.name);
                                 // print(project_ID);
                                });
                              },
                             // value: Project(project_ID,myTest),//selectedProject,
                              isExpanded: false,
                              hint: Text(projectName,
                                style: TextStyle(color: Color(
                                    0xff29B6F6)), //Color(0xff0d53dc)),
                              ),
                            )
                          ]);
                    }
                    return Container(
                      height: 0, width: 0,
                    );
                  }),
            ),

I have created a new page with the following code. I am getting the following error.

The following _TypeError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, dependencies: [MediaQuery], state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#50df7): type 'String' is not a subtype of type 'Project?'

I am not sure how to fix that.

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

var selectedProject;
var idProject;

DocumentSnapshot snap;

class MyTest extends StatefulWidget {
  const MyTest({Key key}) : super(key: key);

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

class _MyTestState extends State<MyTest> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('test'),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.add_circle_outline,
              color: Colors.white,
            ),
            onPressed: () {

            },
          ),
        ],
      ),
      body:

      Padding(
        padding: const EdgeInsets.fromLTRB(8.0, 3.0, 0.0, 0.0),
        child: StreamBuilder<QuerySnapshot>(
            stream: FirebaseFirestore.instance
                .collection('Users')
                .doc(FirebaseAuth.instance.currentUser.uid)
                .collection('projects')
                .snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData)
                const Text("Loading.....");
              else {
                List<DropdownMenuItem <Project>> goalItems = [];
                for (int i = 0; i < snapshot.data.docs.length; i++) {
                  snap = snapshot.data.docs[i];
                  print(snap.id);
                  print(snap['project_Name']);

                  goalItems.add(
                    DropdownMenuItem(
                      value: Project(snap.id, snap['project_Name']),
                      //(snap['project_Name'], snap.id),
                      child: SizedBox(
                        width: MediaQuery
                            .of(context)
                            .size
                            .width * 0.89,
                        child: Text(
                          (snap['project_Name']),
                          style: TextStyle(color: Colors.black),
                        ),
                      ),
                      //  style: TextStyle(color: Color(0xff11b719)),
                      // ),

                    ),
                  );
                }
                return Row(
                    children: <Widget>[
                      DropdownButton <Project>(
                        items: goalItems,
                        onChanged: (Project pro) {
                          setState(() {
                            selectedProject = pro.name;
                            idProject = pro.id;
                           final test4 = Project(idProject,  selectedProject);
                            
                          });
                        },
                         value: selectedProject,
                        isExpanded: false,
                        hint: Text('test',//projectName,
                          style: TextStyle(color: Color(
                              0xff29B6F6)), //Color(0xff0d53dc)),
                        ),
                      )
                    ]);
              }
              return Container(
                height: 0, width: 0,
              );
            }),
      ),
    );
  }
}

class Project {
  // var User(this.name, this.id);
  final String id;
  final String name;

  Project(this.id,this.name);
}

Upvotes: 1

Views: 272

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

You need to use a custom model like Project:

class Project {
  const Project(this.name, this.id);    
  final String name;
  final String id;
}

And instead of adding just the String names to the DropdownButton items add those models:

 List<DropdownMenuItem> goalItems = [];
                      for (int i = 0; i < snapshot.data.docs.length; i++) {
                        DocumentSnapshot snap = snapshot.data.docs[i];
                         test = snapshot.data.docs[i];
                      
                        goalItems.add(
                          DropdownMenuItem(
                            value: Project(snap['project_Name'], snap.id),
                            child: SizedBox(
                              width:MediaQuery.of(context).size.width*0.89,
                              child: Text(
                                (snap['project_Name']),
                                style: TextStyle(color: Colors.black),
                              ),
                            ),

                            //  style: TextStyle(color: Color(0xff11b719)),
                            // ),
                            value: (snap['project_Name']),
                          ),
                        );
                      }

Then you can get the id from the Project on the onClick listener:

return Row(
                          children:<Widget> [
                            DropdownButton(
                              items: goalItems,
                              onChanged: (Project pro) {
                                setState(() {
                                  selectedProject = pro;
                                  taskNewValue ['project_Name'] = pro.name ;
                                  taskNewValue['project_ID'] = pro.id;

//here I am trying to get the id of the record, so I can record the id when the user select save
                                });
                              },
                              value: selectedProject,
                              isExpanded: false,
                              hint:  Text(projectName,
                                style: TextStyle(color: Color (0xff29B6F6)), //Color(0xff0d53dc)),
                              ),
                            )]);
                    }

Upvotes: 1

Related Questions