如何修复 E/flutter (15862): 未处理的异常: 错误状态: 在 flutter 中将数据推送到 firebase 时没有元素?

2024-04-22

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

my code

情态动词

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('', '', '', '', '', ''))));

  }
....
}

和 StudentScreen 小部件代码:

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'),
...
}

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

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,它必须进行推送,但当我这样做时,它会给出上面的错误, 我不知道我必须做什么 我搜索了很长时间这个问题但没有找到任何东西

运行应用程序时也会出现此错误

[错误: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。 (包: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: No Element每当 Dart 尝试访问 List 对象中的空元素时,就会抛出该异常。

Example:

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

=> Bad state: No element

执行上述操作,您将得到一个“Bad State: No element” 抛出异常。

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

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

如果您使用的是 List 方法,例如.firstWhere or .singleWhere你可以指定一个orElse当没有元素或未找到元素时将使用该子句。

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

当没有元素或没有元素与“where”条件匹配时,上面的代码将返回 null。

空安全

随着 Flutter 2 中 Null safe Dart 的发布,.firstWhere called .firstWhereOrNull它可以返回列表的对象类型(如果找到)或 null,在 Iterable 中可用extension里面的类package:collection/collection.dart.

所以上面的内容就变成了:

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

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

其中,如果列表项有id == 1它将被退回,否则,null被返回。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复 E/flutter (15862): 未处理的异常: 错误状态: 在 flutter 中将数据推送到 firebase 时没有元素? 的相关文章

随机推荐