Abdallah El-Rashedy
Abdallah El-Rashedy

Reputation: 871

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

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!

Upvotes: 2

Views: 10099

Answers (2)

Wasib Hussain
Wasib Hussain

Reputation: 256

I also got same error, while working with first.where() method using the List.

I was doing a mistake, I was getting the id which I passed from out side in the method, but mistakenly I was putting that id as string like this:

final existingJournal = _journals.firstWhere((item) => item['id'] == "id");

then i simply put it without string and it worked fine.

final existingJournal = _journals.firstWhere((item) => item['id'] == id);

Upvotes: 0

Baker
Baker

Reputation: 28010

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.

Upvotes: 8

Related Questions