Flutter:未处理的异常:状态不佳:DocumentSnapshotPlatform 中不存在字段,无法正常工作

时间:2021-04-21 07:32:02

标签: snapshot

我是 Flutter 的新手,我正在构建一个 Notes 应用程序。在我的项目中,我创建了三个文件 main.dart、addUser.dart 和 editUser.dart 我的 CREATE 操作(addUser.dart)正常工作和 READ 操作(main.dart),但是当我点击读取操作时,它显示红色带有警告错误状态的错误:DocumentSnapshotPlatform 中不存在字段

我收到此错误:

════════ Exception caught by widgets library ═══════════════════════════════════
The following StateError was thrown building Builder(dirty):
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was
MaterialApp
lib\main.dart:18
When the exception was thrown, this was the stack
#0      DocumentSnapshotPlatform.get._findKeyValueInMap
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:82
#1      DocumentSnapshotPlatform.get._findComponent
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:98
#2      DocumentSnapshotPlatform.get
package:cloud_firestore_platform_interface/…/platform_interface/
platform_interface_document_snapshot.dart:113
#3      DocumentSnapshot.get
package:cloud_firestore/src/document_snapshot.dart:49
#4      DocumentSnapshot.[]
package:cloud_firestore/src/document_snapshot.dart:56
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 2 of 826 libraries in 14,160ms.
Restarted application in 11,595ms.
W/DynamiteModule(10940): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(10940): Considering local module providerinstaller:0 and remote module 
providerinstaller:0
W/ProviderInstaller(10940): Failed to load providerinstaller module: No acceptable module found. 
Local version is 0 and remote version is 0.

════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during layout:
A RenderFlex overflowed by 240 pixels on the bottom.

The relevant error-causing widget was
Column
lib\main.dart:96
To inspect this widget in Flutter DevTools, visit: http://127.0.0.1:9101/#/inspector? 
uri=http%3A%2F%2F127.0.0.1%3A52941%2F0C0SU5iODJs%3D%2F&inspectorRef=inspector-0
The overflowing RenderFlex has an orientation of Axis.vertical.
The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and 
black striped pattern. This is usually caused by the contents being too big for the RenderFlex.

Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the 
RenderFlex to fit within the available space instead of being sized to their natural size.
This is considered an error condition because it indicates that there is content that cannot be seen. 
If the content is legitimately bigger than the available space, consider clipping it with a ClipRect 
widget before putting it in the flex, or using a scrollable container rather than a Flex, like a 
ListView.

The specific RenderFlex in question is: RenderFlex#b9fbf relayoutBoundary=up10 OVERFLOWING
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
A RenderFlex overflowed by 240 pixels on the bottom.
The relevant error-causing widget was
Column
lib\main.dart:96
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was
MaterialApp
lib\main.dart:18
════════════════════════════════════════════════════════════════════════════════

我的Main.dart文件

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:darwish_latest/addNote.dart';
import 'package:darwish_latest/editNote.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
CollectionReference ref = FirebaseFirestore.instance.collection('darwish');
@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: Text("UMHE Note"),
    ),
    floatingActionButton: FloatingActionButton(
        // backgroundColor: Colors.black,
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (_) => AddNote()));
        }),
    body: StreamBuilder(
      stream: FirebaseFirestore.instance
          .collection("darwish")
          .orderBy("time")
          .snapshots(),
      builder: (context, snapshot) {
        return ListView.builder(
            itemCount:
                snapshot.hasData ? snapshot.data.documents.length : 0,
            itemBuilder: (_, index) {
              var darwish = snapshot.data.documents[index];
              return snapshot.data.documents.length == 0
                  ? Text("Text Notes Found")
                  : GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (_) => EditNote(
                                    darwish['empId'], darwish.id)));
                      },
                      child: Container(
                        margin: EdgeInsets.all(10),
                        constraints: BoxConstraints(maxHeight: 150),
                        color: Colors.grey.withOpacity(0.4),
                        child: Column(children: [
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['empid'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['user'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['email'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['password'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['DOB'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(20.0),
                            child: Text(darwish['address'],
                                style: GoogleFonts.sourceCodePro(
                                    fontSize: 20)),
                          ),
                        ]),
                      ),
                    );
            });
      },
    ));
}
}

我的addNote.dart文件

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

class AddNote extends StatefulWidget {
@override
_AddNoteState createState() => _AddNoteState();
}

class _AddNoteState extends State<AddNote> {
GlobalKey<FormState> formKey = GlobalKey<FormState>();

TextEditingController empId = TextEditingController();
TextEditingController user = TextEditingController();
TextEditingController emailid = TextEditingController();
TextEditingController passwordd = TextEditingController();
TextEditingController dobirth = TextEditingController();
TextEditingController myaddress = TextEditingController();

CollectionReference ref = FirebaseFirestore.instance.collection('darwish');

String empid = '';
String username = '';
String email = '';
String password = '';
String dob = '';
String address = '';

buildEmployeeid() => TextFormField(
    controller: empId,
    decoration: InputDecoration(
      labelText: 'Employee Id',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Employee id can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => empid = value),
  );

Widget buildUsername() => TextFormField(
    controller: user,
    decoration: InputDecoration(
      labelText: 'Username',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Title can not be empty';
      }
      return null;
    },
    maxLength: 30,
    onSaved: (value) => setState(() => username = value),
  );

Widget buildEmail() => TextFormField(
    controller: emailid,
    decoration: InputDecoration(
      labelText: 'Email',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      final pattern =
          r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
      final regExp = RegExp(pattern);
      if (value.isEmpty) {
        return 'Email can not be empty';
      } else if (!regExp.hasMatch(value)) {
        return 'Enter a valid email';
      }
      return null;
    },
    keyboardType: TextInputType.emailAddress,
    onSaved: (value) => setState(() => email = value),
  );

Widget buildPassword() => TextFormField(
    controller: passwordd,
    decoration: InputDecoration(
      labelText: 'Password',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Password can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => password = value),
    obscureText: true,
  );

buildDOB() => TextFormField(
    controller: dobirth,
    decoration: InputDecoration(
      labelText: 'Date Of Birth',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Date of Birth can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => dob = value),
  );

buildAddress() => TextFormField(
    controller: myaddress,
    decoration: InputDecoration(
      labelText: 'Address',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Address can not be empty';
      }
      return null;
    },
    maxLength: 30,
    onSaved: (value) => setState(() => address = value),
  );

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    centerTitle: true,
    title: Text(
      'UMHE Form',
    ),
  ),
  body: Form(
    key: formKey,
    // autovalidate: true,
    child: ListView(
      padding: EdgeInsets.all(16),
      children: [
        buildEmployeeid(),
        const SizedBox(height: 32),
        buildUsername(),
        const SizedBox(height: 16),
        buildEmail(),
        const SizedBox(height: 32),
        buildPassword(),
        const SizedBox(height: 32),
        buildDOB(),
        const SizedBox(height: 32),
        buildAddress(),
        const SizedBox(height: 32),
        ElevatedButton(
            child: Text(
              'Submit',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
              ),
            ),
            onPressed: () {
              final isValid = formKey.currentState.validate();
              FocusScope.of(context).unfocus();
              if (isValid) {
                // formKey.currentState.save();
                ref.add({
                  'empid': empId.text,
                  'user': user.text,
                  'email': emailid.text,
                  'password': passwordd.text,
                  'DOB': dobirth.text,
                  'address': myaddress.text,
                  'time': DateTime.now()
                });
                formKey.currentState.reset();
                return AlertDialog(
                  content: Text('Saved Successfully...'),
                );
              }
            }),
      ],
    ),
  ),
);
}
}

我的myEdit.dart文件

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

class EditNote extends StatefulWidget {
 String id;
 String docid;
 EditNote(id, docid);
 @override
 _EditNoteState createState() => _EditNoteState();
}

class _EditNoteState extends State<EditNote> {
 GlobalKey<FormState> formKey = GlobalKey<FormState>();

 TextEditingController empId = TextEditingController();
 TextEditingController user = TextEditingController();
 TextEditingController emailid = TextEditingController();
 TextEditingController passwordd = TextEditingController();
 TextEditingController dobirth = TextEditingController();
 TextEditingController myaddress = TextEditingController();

@override
 void initState() {
 empId.text = widget.id;
 }

CollectionReference ref = FirebaseFirestore.instance.collection("darwish");

editEmployeeId() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Employee Id can not be empty';
      }
      return null;
    },
    controller: empId,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'Employee Id',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

editUser() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'User can not be empty';
      }
      return null;
    },
    controller: user,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'User',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

editEmailId() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Email Id can not be empty';
      }
      return null;
    },
    controller: emailid,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'Email Id',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

editPassword() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Password can not be empty';
      }
      return null;
    },
    controller: passwordd,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'Password',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

editDOB() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'DOB can not be empty';
      }
      return null;
    },
    controller: dobirth,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'Date Of Birth',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

editMyAddress() => TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Address can not be empty';
      }
      return null;
    },
    controller: myaddress,
    decoration: InputDecoration(
      // fillColor: Colors.grey.withOpacity(0.4),
      filled: true,
      hintText: 'Employee Id',
    ),
    style: GoogleFonts.sourceCodePro(
        fontSize: 25,
        // color: Colors.black,
        fontWeight: FontWeight.bold),
  );

@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: Text("Edit Note"),
      leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () => {Navigator.pop(context)}),
      actions: [
        IconButton(
            icon: Icon(
              Icons.delete,
              color: Colors.white,
            ),
            onPressed: () {
              FirebaseFirestore.instance
                  .collection('darwish')
                  .doc(widget.docid)
                  .delete()
                  .then((value) => Navigator.pop(context));
            }),
      ],
    ),
    body: Form(
        key: formKey,
        child: ListView(
          padding: EdgeInsets.all(16),
          children: [
            editEmployeeId(),
            const SizedBox(height: 16),
            editUser(),
            const SizedBox(height: 32),
            editEmailId(),
            const SizedBox(height: 32),
            editPassword(),
            const SizedBox(height: 32),
            editDOB(),
            const SizedBox(height: 32),
            editMyAddress(),
            ElevatedButton(
                child: Text(
                  'Update',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                onPressed: () {
                  if (formKey.currentState.validate()) {
                    FirebaseFirestore.instance
                        .collection("darwish")
                        .doc(widget.docid)
                        .set({
                      'empid': empId.text,
                      'user': user.text,
                      'email': emailid.text,
                      'password': passwordd.text,
                      'DOB': dobirth.text,
                      'address': myaddress.text,
                      // 'content': content.text,
                      'time': DateTime.now()
                    }).then((value) => Navigator.pop(context));
                  }
                }),
          ],
        )));
}
}

0 个答案:

没有答案