简体   繁体   中英

Bad State when connecting to Firebase data to update

So, i wanted to make me a flutter page that takes the data from a collection in firebase and display the entries based on title, and when i press on a title it display the full data from the entry. Then, in the detail page after the data make a big textbox that the user can introduce data, and a submit button. The data from the textbox updates the response field in the table.

This is my code that i worked upon. Keep note that i am a beginner and i might have made a rookie mistake here and there:

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

class ResponsePage extends StatefulWidget {
  @override
  _ResponsePageState createState() => _ResponsePageState();
}

class _ResponsePageState extends State<ResponsePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF006400),
        title: Text('Visualize Personal'),
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('personal').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) {
              final form = snapshot.data!.docs[index];

              return ListTile(
                title: Text(form['title']),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DetailPage(form: form),
                    ),
                  );
                },
              );
            },
          );
        },
      ),
    );
  }
}

class DetailPage extends StatefulWidget {
  DetailPage({Key? key, required this.form}) : super(key: key);

  final DocumentSnapshot form;
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  final TextEditingController _responseController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Detail Page')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Display the data for the entry
            Text('Title: ${widget.form['title']}'),
            Text('Description: ${widget.form['description']}'),
            Text('Name: ${widget.form['name']}'),
            Text('Number: ${widget.form['number']}'),
            Text('Response: ${widget.form['response']}'),
            Text('Street: ${widget.form['street']}'),
            Text('Type: ${widget.form['type']}'),
            SizedBox(height: 16.0),
            // Add the text field and submit button
            TextField(
              controller: _responseController,
              decoration: InputDecoration(
                labelText: 'Response',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 8.0),
            ElevatedButton(
              child: Text('Submit'),
              onPressed: () {
                // Update the response field in the Firebase collection
                FirebaseFirestore.instance
                    .collection('your_collection')
                    .doc(widget.form.id)
                    .update({
                  'response': _responseController.text,
                });
                Navigator.pop(context);
              },
            )
          ],
        ),
      ),
    );
  }
}

I searched on stack overflow for my error message (red screen with yellow writing): Bad State: field does not exist within the DocumentSnapshotPlatform, but it cannot find a relatable answers for my code. Please help?

docs[index] is documentsnapshot using firebase extension.data() to convert the documentsnapshot to map<string,dynamic>

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

class ResponsePage extends StatefulWidget {
  @override
  _ResponsePageState createState() => _ResponsePageState();
}

class _ResponsePageState extends State<ResponsePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF006400),
        title: Text('Visualize Personal'),
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('personal').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) {
              final form = snapshot.data!.docs[index].data() as Map<String,dynamic>;


              return ListTile(
                title: Text(form['title']),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DetailPage(form: form),
                    ),
                  );
                },
              );
            },
          );
        },
      ),
    );
  }
}

class DetailPage extends StatefulWidget {
  DetailPage({Key? key, required this.form}) : super(key: key);

  final DocumentSnapshot form;
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  final TextEditingController _responseController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Detail Page')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Display the data for the entry
            Text('Title: ${widget.form['title']}'),
            Text('Description: ${widget.form['description']}'),
            Text('Name: ${widget.form['name']}'),
            Text('Number: ${widget.form['number']}'),
            Text('Response: ${widget.form['response']}'),
            Text('Street: ${widget.form['street']}'),
            Text('Type: ${widget.form['type']}'),
            SizedBox(height: 16.0),
            // Add the text field and submit button
            TextField(
              controller: _responseController,
              decoration: InputDecoration(
                labelText: 'Response',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 8.0),
            ElevatedButton(
              child: Text('Submit'),
              onPressed: () {
                // Update the response field in the Firebase collection
                FirebaseFirestore.instance
                    .collection('your_collection')
                    .doc(widget.form.id)
                    .update({
                  'response': _responseController.text,
                });
                Navigator.pop(context);
              },
            )
          ],
        ),
      ),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM