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

问题描述

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

我的代码

情态的

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'];
  }
}

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): [ERROR: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 (package:flutter_app/ui/listview_student.dart:82:37)

它只是用于测试和了解学生的应用程序,StudentList 小部件用于显示学生列表,StudentScreen 用于添加或编辑学生,因此如果我按下此平面按钮,它必须进行推送,但当我这样做时它会给出上述错误,我不'不知道我必须做什么我搜索了很长时间关于这个问题,我没有找到任何东西

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

[错误:flutter/lib/ui/ui_dart_state.cc(157)] 未处理的异常:'String' 类型不是'index' E/flutter (15862) 的'int' 类型的子类型:#0 new 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 (package:flutter/src/widgets/framework.dart:1148:30) E/flutter (15862) : #3 ListViewStudentState._onStudentAdded (package:flutter_app/ui/listview_student.dart:77:5)

可以帮忙吗!

标签: flutterdart

解决方案


Bad State: No Element每当 Dart 试图访问一个空的 List 对象中的元素时,就会抛出StateError of 。

例子:

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

=> Bad state: No element

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

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

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

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

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

每当没有元素或没有元素与“where”条件匹配时,上述内容将返回 null。

空安全

随着 Flutter 2 中 Null 安全 Dart 的发布,一个可以返回 List 的 Object 类型(如果找到)或 null的.firstWhere调用版本在 Iterable类中可用。.firstWhereOrNullextensionpackage: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被返回。


推荐阅读