skip to Main Content

I followed a tutorial by Mitch Koko:

Firebase CRUD Operation

I made some modification to the save code as below:

Future<void> addNewNote(String noteheader, String noteContent) { 
  return notes.add({ 'note' :{ 'header': noteHeader, 'content': noteContent, },
    'timestamp': Timestamp.now()
  });
}

and the notes are stored as below

Data Stored in Firebase

The problem is I can’t fetch the data according to the initial place I made, for header and content part.

I tried code below:

  body: StreamBuilder<QuerySnapshot>(
    stream: firestoreService.getNotesStream(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        // Load the data
        List notesList = snapshot.data!.docs;

        // Display the data as list
        return ListView.builder(
          itemCount: notesList.length,
          itemBuilder: (context, index) {
            //? Get each Document
            DocumentSnapshot document = notesList[index];
            String docId = document.id;

            //? Get note from each doc
            Map<String, dynamic> data =
                document.data() as Map<String, dynamic>;

            String noteHeader = data['note'];
            // String noteContent = data['note': ];

            //? Display as a ListTile
            return ListTile(
              title: Text(noteHeader),
              // subtitle: Text(noteContent),
            );
          },
        );
      } else {
        //? If no notes
        return const Text('No Notes');
      }
    },
)
 

how can I map it correctly using the same format? Or at least I can understand using the syntax I used previously

2

Answers


  1. Chosen as BEST ANSWER

    It's okay, I got my answer while trying out putting it as key:key:value pair, I made the changes as below:

    Map<String, dynamic> data =
    document.data() as Map<String, dynamic>;
    String noteHeader = data['note']['header']; <-- Add here as another key
            
    

  2. This line in your code doesn’t match with the data structure in your screenshot:

    String noteHeader = data['note'];
    

    Since the note field in your screenshot is a map, you’ll need to use a Map:

    Map noteMap = data['note'] as Map;
    

    Then you can get the header from that with:

    String noteHeader = noteMap['header'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search