如何修复E/flutter(15862):未处理的异常:错误状态:在扑扑中将数据推送到Firebase时没有元素? [英] how to fix E/flutter (15862): Unhandled Exception: Bad state: No element when push data to firebase in flutter?

查看:57
本文介绍了如何修复E/flutter(15862):未处理的异常:错误状态:在扑扑中将数据推送到Firebase时没有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将数据发送到Firebase,我做了所有事情这是我的代码

我的代码

模态

  import'package:firebase_database/firebase_database.dart';班级学生{字符串_id;字符串_name;字符串_age;字符串_city;字符串_department;字符串_description;学生(this._id,this._name,this._age,this._city,this._department,this._description);Student.map(动态obj){this._id = obj ['id'];this._name = obj ['name'];this._age = obj ['age'];this._city = obj ['city'];this._department = obj ['department'];this._description = obj ['_ description'];}字符串获取ID =>_ID;字符串获取名称=>_名称;字符串获取年龄=>_年龄;字符串get city =>_城市;字符串获取部门=>_部门;字符串获取说明=>_描述;Student.fromSnapShot(DataSnapshot快照){_id = snapshot.value ['id'];_name = snapshot.value ['name'];_age = snapshot.value ['age'];_city = snapshot.value ['city'];_department = snapshot.value ['department'];_description = snapshot.value ['_ description'];}} 

  final studentRef = FirebaseDatabase.instance.reference().child('student');....类ListViewStudentState扩展了State< ListViewStudent>{List< Student>_学生们;StreamSubscription< Event>_onStudentAddedSub;}StreamSubscription< Event>_onStudentChangedSub;@override无效的initState(){_students = List();_onStudentAddedSub = studentRef.onChildAdded.listen(_onStudentAdded);_onStudentChangedSub = studentRef.onChildChanged.listen(_onStudentChanged);super.initState();}@override无效dispose(){//TODO:实现处置super.dispose();_onStudentAddedSub.cancel();_onStudentChangedSub.cancel();}...void _onStudentAdded(Event event){setState((){_students.add(Student.fromSnapShot(event.snapshot));});}void createNewStudent(BuildContext context)异步{等待Navigator.push(context,MaterialPageRoute(builder:(context)=> StudentScreen(Student('',``,'',``,``,'','')))));}....} 

和StudentScreen窗口小部件代码:

  class StudentScreen扩展了StatefulWidget {最终学生;StudentScreen(this.student);@override状态< StatefulWidget>createState(){//TODO:实现createState返回StudenScreenState();}}类StudenScreenState扩展了State< StudentScreen>.{TextEditingController _nameController;TextEditingController _ageController;TextEditingController _cityController;TextEditingController _deptController;TextEditingController _noteController;@override无效的initState(){_nameController = TextEditingController(text:widget.student.name);_ageController = TextEditingController(text:widget.student.age);_cityController = TextEditingController(text:widget.student.city);_deptController = TextEditingController(text:widget.student.department);_noteController = TextEditingController(text:widget.student.description);super.initState();}....FlatButton(onPressed:(){if(widget.student.id!= null){studentRef.child(widget.student.id).set({'名称':_nameController.text,'age':_ageController.text,'city':_cityController.text,'部门':_deptController.text,'_description':_noteController.text,}).然后((_){Navigator.pop(上下文);});}别的 {studentRef.push().set({'名称':_nameController.text,'age':_ageController.text,'city':_cityController.text,'部门':_deptController.text,'_description':_noteController.text,}).然后((_){Navigator.pop(上下文);});}},孩子:(widget.student.id!= null)?文本(更新"):文本(添加"),...} 

当尝试推送数据时,它给了我这个错误

E/flutter(15862):[错误:flutter/lib/ui/ui_dart_state.cc(157)]未处理的异常:错误状态:无元素E/flutter(15862):#0 ListMixin.singleWhere(dart:collection/list.dart:185:5)E/flutter(15862):#1 ListViewStudentState._onStudentChanged(软件包:flutter_app/ui/listview_student.dart:82:37)

这只是用于测试和了解学生的应用程序有用于显示学生列表的StudentList小部件和用于添加或编辑学生的StudentScreen因此,如果我按下这个Flatbutton的话,它必须进行推动,但是在执行此操作时会出现上面的错误,我不知道该怎么办我搜索了很长时间的问题,但没有发现任何东西

,并且在运行应用程序时也会给出此错误

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)]未处理的异常:类型'String'不是'index'的'int'类型的子类型E/flutter(15862):#0新Student.fromSnapShot(软件包:flutter_app/_modal/student.dart:28:25)E/flutter(15862):#1 ListViewStudentState._onStudentAdded.(package:flutter_app/ui/listview_student.dart:78:29)E/flutter(15862):#2 State.setState(包:flutter/src/widgets/framework.dart:1148:30)E/flutter(15862):#3 ListViewStudentState._onStudentAdded(软件包:flutter_app/ui/listview_student.dart:77:5)

可以帮助您!

解决方案

Bad State:错误的状态错误:每当Dart尝试访问List对象中为空的元素时,都不会引发任何元素.

示例:

  List< Foo>foos = [];foos.first;=>不良状态:无元素 

执行上述操作,您将获得"错误状态:无元素"引发异常.

为避免这种情况,您必须在尝试访问任何元素之前检查列表是否为空.

  if(foos!= null&& foos.isNotEmpty)foos.first; 

如果您使用诸如 .firstWhere .singleWhere 之类的List方法,则可以指定 orElse 子句,该子句将在没有元素或找不到元素.

  foos.firstWhere((e)=> e.id == 1,否则Else:()=> null); 

每当没有元素或没有元素与"where"匹配时,以上内容将返回null.条件.

空安全

随着Flutter 2中Null安全Dart的发布,称为 .firstWhereOrNull .firstWhere 版本可以返回列表的Object类型(如果找到),或为null,可在 package:collection/collection.dart 内的Iterable extension 类中使用.

因此上述内容将变为:

  import'package:collection/collection.dart';//不要忘记在文件顶部oo?firstFoo = foos.firstWhereOrNull((e)=> e.id == 1); 

如果列表项具有 id == 1 ,则将返回该列表项,否则,将返回 null .

i trying to send data to firebase i did every thing this my code

my code

the modal

import 'package:firebase_database/firebase_database.dart';

class Student {
  String _id;
  String _name;
  String _age;
  String _city;
  String _department;
  String _description;
  Student(this._id, this._name, this._age, this._city, this._department, this._description);

  Student.map(dynamic obj) {
    this._id = obj['id'];
    this._name = obj['name'];
    this._age = obj['age'];
    this._city = obj['city'];
    this._department = obj['department'];
    this._description = obj['_description'];
  }
  String get id => _id;
  String get name => _name;
  String get age => _age;
  String get city => _city;
  String get department => _department;
  String get description => _description;

  Student.fromSnapShot(DataSnapshot snapshot){
    _id = snapshot.value['id'];
    _name = snapshot.value['name'];
    _age = snapshot.value['age'];
    _city = snapshot.value['city'];
    _department = snapshot.value['department'];
    _description = snapshot.value['_description'];
  }
}

and

final studentRef = FirebaseDatabase.instance.reference().child('student');
....
class ListViewStudentState extends State<ListViewStudent> {
List<Student> _students;
  StreamSubscription<Event> _onStudentAddedSub;
}
 StreamSubscription<Event> _onStudentChangedSub;
  @override
  void initState() {
    _students = List();
    _onStudentAddedSub = studentRef.onChildAdded.listen(_onStudentAdded);
    _onStudentChangedSub = studentRef.onChildChanged.listen(_onStudentChanged);

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _onStudentAddedSub.cancel();
    _onStudentChangedSub.cancel();
  }

...
void _onStudentAdded(Event event) {
    setState(() {
      _students.add(Student.fromSnapShot(event.snapshot));
    });
  }
 void createNewStudent(BuildContext context) async{
    await Navigator.push(context, MaterialPageRoute(builder: (context)=> StudentScreen(Student('', '', '', '', '', ''))));

  }
....
}

and the StudentScreen widget code:

class StudentScreen extends StatefulWidget {
  final Student student;
  StudentScreen(this.student);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return StudenScreenState();
  }

}

class StudenScreenState extends State<StudentScreen> {
  TextEditingController _nameController;
  TextEditingController _ageController;
  TextEditingController _cityController;
  TextEditingController _deptController;
  TextEditingController _noteController;

  @override
  void initState() {
    _nameController = TextEditingController(text: widget.student.name);
    _ageController = TextEditingController(text: widget.student.age);
    _cityController = TextEditingController(text: widget.student.city);
    _deptController = TextEditingController(text: widget.student.department);
    _noteController = TextEditingController(text: widget.student.description);
    super.initState();
  }
....
FlatButton(
onPressed:(){
 if(widget.student.id != null){
 studentRef.child(widget.student.id).set({
 'name': _nameController.text,
 'age': _ageController.text,
 'city': _cityController.text,
 'department': _deptController.text,
 '_description': _noteController.text,

 }).then((_){
 Navigator.pop(context);
  });
}else {
 studentRef.push().set({
 'name': _nameController.text,
 'age': _ageController.text,
 'city': _cityController.text,
 'department': _deptController.text,
 '_description': _noteController.text,
 }).then((_){
  Navigator.pop(context);
 });
 }
},
 child: (widget.student.id != null)? Text('Update'): Text('Add'),
...
}

it's gives me this error when try to push the data

E/flutter (15862): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Bad state: No element E/flutter (15862): #0 ListMixin.singleWhere (dart:collection/list.dart:185:5) E/flutter (15862): #1 ListViewStudentState._onStudentChanged (package:flutter_app/ui/listview_student.dart:82:37)

It's just app for test and learning about student there the StudentList widget for show list of the student and StudentScreen for Add or Edit student so it must doing push if i pressed on this Flatbutton but it's gives the error above when i do it, i don't know what i must to do i searched for long time about the problem and i didn't found anything

and it's gives this error too when run the app

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' E/flutter (15862): #0 new Student.fromSnapShot (package:flutter_app/_modal/student.dart:28:25) E/flutter (15862): #1 ListViewStudentState._onStudentAdded. (package:flutter_app/ui/listview_student.dart:78:29) E/flutter (15862): #2 State.setState (package:flutter/src/widgets/framework.dart:1148:30) E/flutter (15862): #3 ListViewStudentState._onStudentAdded (package:flutter_app/ui/listview_student.dart:77:5)

can help please!

解决方案

StateError of Bad State: No Element is thrown whenever Dart tries to access an element inside a List object which is empty.

Example:

List<Foo> foos = [];
foos.first;

=> Bad state: No element

Do the above and you'll get a "Bad State: No element" exception thrown.

To avoid this you have to check whether your list is empty before trying to access any element.

if (foos != null && foos.isNotEmpty)
  foos.first;

If you're using a List method such as .firstWhere or .singleWhere you can specify an orElse clause which will be used when there are no elements or no elements found.

foos.firstWhere((e) => e.id == 1, orElse: () => null);

The above will return null whenever there are no elements or when no element matches the "where" criteria.

Null Safe

With the release of Null safe Dart in Flutter 2, a version of .firstWhere called .firstWhereOrNull which can return either the Object type of your List (if found), or null, is available in an Iterable extension class inside package:collection/collection.dart.

So the above would become:

import 'package:collection/collection.dart'; // don't forget this at top of file

Foo? firstFoo = foos.firstWhereOrNull((e) => e.id == 1);

Where, if a list item has id == 1 it will be returned, else, null is returned.

这篇关于如何修复E/flutter(15862):未处理的异常:错误状态:在扑扑中将数据推送到Firebase时没有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆