Pheerapon
Pheerapon

Reputation: 21

flutter: NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("User")

I need help

Future<void> getGenderUser(
  {User firebaseUser, String token, BuildContext context}) async {
await Config.initializeClient(token)
    .value
    .query(QueryOptions(
        document: gql(Queries.getGender),
        variables: <String, dynamic>{'id': firebaseUser.uid}))
    .then((value) {
  Navigator.of(context).pop();
  if (value.data['User'][0]['gender'] == null) {
    Navigator.of(context).pushNamed(Routes.welcome);
  } else {
    Navigator.of(context)
        .pushNamed(Routes.homeScreen, arguments: const HomeScreen());
  }
});
}

Error

flutter: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("User")
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
#0      List.[] (dart:core-patch/growable_array.dart:254:60)
#1      OptionLogin.getGenderUser.<anonymous closure>(package:flutter_habit_run/feature/walkthrough/widget/option_login.dart:34:29)
#2      _rootRunUnary (dart:async/zone.dart:1362:47)
#3      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
#4      OptionLogin.getGenderUser (package:flutter_habit_run/feature/walkthrough/widget/option_login.dart:27:5)
#5 OptionLogin.signIn. (package:flutter_habit_run/feature/walkthrough/widget/option_login.dart:51:11) #6 OptionLogin.signIn (package:flutter_habit_run/feature/walkthrough/widget/option_login.dart:47:7)

Upvotes: 2

Views: 243

Answers (2)

Mithson
Mithson

Reputation: 1782

first check whether your value is not null and if not then give this a try by casting your right hand side code to User by adding as User this might help and comment if there any changes in error.

Upvotes: 0

Pat9RB
Pat9RB

Reputation: 650

Without having your source line numbers...

if (value.data['User'][0]['gender'] == null) {

value.data['User'] is probably returning an empty list. i.e. a List exists but there is no users or items in the list. When you ask for the first item [0] there's no item to return. You could add this check into your if...

if (value.data['User'].isEmpty || value.data['User'][0]['gender'] == null) {

You might also need to check if the empty list is the result of an error condition.

Upvotes: 1

Related Questions