how to fix E/flutter (15862): Unhandled Exception: Bad state: No element when push data to firebase in flutter?

亡梦爱人 提交于 2021-02-11 13:50:30

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/59795606/how-to-fix-e-flutter-15862-unhandled-exception-bad-state-no-element-when-pu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!