oha
oha

Reputation: 11

Bad state: No element flutter

I am developing a small project based on contact management in which I integrated the 'contact service' flutter plugin and when I browse the contacts from my physical device there are display errors here is my code

 for (int i=0;i<ccl.contacts.length;i++){
      if(ccl.contacts[i].phones.first.value.toString() != null && ccl.contacts[i].phones.first.value.toString().length>0){

      print(ccl.contacts[i].phones.first.value.toString().trim());
      print(ccl.contacts[i].displayName);

this is my error

 Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following StateError was thrown while handling a gesture:
Bad state: No element

When the exception was thrown, this was the stack: 
#0      ListIterable.first (dart:_internal/iterable.dart:51:22)
#1      _MyHomePageState.changedContact (package:contactchanged/main.dart:74:33)
#2      _MyHomePageState.build.<anonymous closure>.<anonymous closure> (package:contactchanged/main.dart:114:36)
#3      State.setState (package:flutter/src/widgets/framework.dart:1233:30)
#4      _MyHomePageState.build.<anonymous closure> (package:contactchanged/main.dart:114:23)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#70bc3
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(188.6, 115.4)
  finalLocalPosition: Offset(188.6, 29.1)
  button: 1
  sent tap down

Upvotes: 0

Views: 1753

Answers (1)

tehprofessor
tehprofessor

Reputation: 3013

Looks like you have an empty list for one of the contacts phones, and when you call .first on it; raises an error: https://api.dart.dev/stable/2.10.4/dart-core/List/first.html

You want something like the following where you check to make sure the list isNotEmpty before calling first on it:

if (ccl.contacts[i].phones.isNotEmpty) {
  print(ccl.contacts[i].phones.first.value.toString().trim());
  print(ccl.contacts[i].displayName);
}

Upvotes: 1

Related Questions