Home > Blockchain >  NoSuchMethodError : '[]' in flutter
NoSuchMethodError : '[]' in flutter

Time:01-07

I am working on flutter and i have overriden initState() and overriden Widget build() So when i assigned value to a variable inside overriden initState() and using that variable inside the overriden Widget build(), i am getting the variable as null. someone please help me

dynamic database_functions = FirebaseMethods();

class RenderProfileView extends StatefulWidget {
  String email;
  RenderProfileView(this.email, {super.key});

  @override
  State<RenderProfileView> createState() => _RenderProfileViewState();
}

class _RenderProfileViewState extends State<RenderProfileView> {
  TextEditingController name_controller = TextEditingController();
  TextEditingController phone_number_controller = TextEditingController();

  dynamic? user_json;  // this is the variable i am assigning value inside initState()

  String name = "";
  String phone_number = "";
  dynamic edit_or_display_name = ProfileName();
  dynamic edit_or_display_phone_number = ProfilePhoneNumber();
  dynamic edit_or_save_icon = Icons.edit;
  dynamic edit_or_save_text = "Edit";
  String error_message = "";

  @override
  void initState() {
    super.initState();
    getUserData();
  }

  void getUserData() {
    database_functions.findUsers('email', widget.email).then((value) {
      setState(() {
        print(value);  // this line not executing before the print statement that i have given in the Widget build()
        user_json = value;
        name = value[0].name;
        phone_number = value[0].phone;
      });
    });
  }

  dynamic get_name() {
    return name_controller.text;
  }

  void clear_name() {
    name_controller.text = "";
  }

  dynamic get_phone_number() {
    return phone_number_controller.text;
  }

  void clear_phone_number() {
    phone_number_controller.text = "";
  }

  void changer() {
    setState(() {
      if (edit_or_display_name.runtimeType == NameField) {
        String newName = get_name();
        String newPhoneNumber = get_phone_number();
        if (name_validator(newName) == true && phone_number_validator(newPhoneNumber) == true) {
          name = newName;
          phone_number = newPhoneNumber;
          clear_name();
          clear_phone_number();
          edit_or_display_name = ProfileName();
          edit_or_display_phone_number = ProfilePhoneNumber();
          edit_or_save_icon = Icons.edit;
          edit_or_save_text = "Edit";
          error_message = "";
        } else {
          if (name_validator(newName) == false) {
            error_message = "Invalid format for name!";
          } else {
            error_message = "Invalid format for phone number!";
          }
        }
      } else {
        edit_or_display_name = NameField(name_controller, get_name, clear_name);
        edit_or_display_phone_number = PhoneNumberField(phone_number_controller, get_phone_number, clear_phone_number);
        edit_or_save_icon = Icons.save;
        edit_or_save_text = "Save";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    print(user_json);  // this is giving me null
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Profile'),
          actions: <Widget>[
            TextButton(
              style: flatButtonStyle,
              onPressed: () => changer(),
              child: IconTextPair(edit_or_save_icon, edit_or_save_text, Colors.white,),
            ),
          ],
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white,
        ),
        backgroundColor: Colors.white,
        body: ProfilePage(name, widget.email, user_json[0]['rollno'], phone_number, user_json[0].batch, user_json[0].dept, user_json[0].gender, ["a", "b", "c", "d"], user_json[0].photoImgLink, edit_or_display_name, edit_or_display_phone_number, error_message),  // this line gives me the following error : Error: NoSuchMethodError: '[]'
      ),
    );
  }
}

and this is my firebase functions' class

class FirebaseMethods {
  Future<List> findEvents(dynamic attribute, dynamic value) async {
    CollectionReference eventCollection =
        FirebaseFirestore.instance.collection('events');
    return eventCollection
        .where(attribute, isEqualTo: value)
        .get()
        .then((QuerySnapshot querySnapshot) {
      List events = [];
      querySnapshot.docs.forEach((doc) {
        events.add(doc.data());
      });
      return events;
    }).catchError((error) {
      print("Failed to retrieve events: $error");
    });
  }

  Future<List> findUsers(dynamic attribute, dynamic value) async {
    CollectionReference userCollection =
        FirebaseFirestore.instance.collection('profile');
    return userCollection
        .where(attribute, isEqualTo: value)
        .get()
        .then((QuerySnapshot querySnapshot) {
      List users = [];
      querySnapshot.docs.forEach((doc) {
        users.add(doc.data());
      });
      return users;
    }).catchError((error) {
      print("Failed to retrieve users: $error");
    });
  }
}

someone please help me

CodePudding user response:

Widgets' build method may be called before user_json is set since getUserData is called.

You should handle case where user_json == null, such as display loading view.

CodePudding user response:

It is a huge mistake that you are using setState. Just remove it from getUserData. The mistake is trying to execute setState inside initState method. Secondly why you are getting null. Because getting data takes some time. In other words it is async. So you need to print it after it returns some data.

CodePudding user response:

You are calling firebase function which is returning Future. So initially until you get the result it will not update the values & your build will try to access the variables before they are updated.

You can try FutureBuilder in Scaffold's body to fix this.

body: FutureBuilder<String>(
    future: findUsers('email', widget.email),
    builder: (
      BuildContext context,
      AsyncSnapshot<String> snapshot,
    ) {
      // You can check the state of future before rendering widgets
      if (snapshot.connectionState == ConnectionState.waiting) {
        return CircularProgressIndicator();
      } else if (snapshot.connectionState == ConnectionState.done) {
        if (snapshot.hasError) {
          return const Text('Error');
        } else if (snapshot.hasData) {
      // Here in snapshot.data you will not get the list of users
          const userList = snapshot.data as List; 
          return ProfilePage(name, widget.email, userList[0]['rollno'], phone_number, userList[0].batch, userList[0].dept, userList[0].gender, ["a", "b", "c", "d"], userList[0].photoImgLink, edit_or_display_name, edit_or_display_phone_number, error_message);
        } else {
          return const Text('Empty data');
        }
      } else {
        return Text('State: ${snapshot.connectionState}');
      }
    },
  )

CodePudding user response:

You need make getUserData() method async and call it inside your initState.

@override
void initState() {
  super.initState();
  
  WidgetsBinding.instance.addPostFrameCallback((_){
    getUserData();
  });

}

Future<void> getUserData() async {
    database_functions.findUsers('email', widget.email).then((value) {
      setState(() {
        print(value);  // this line not executing before the print statement that i have given in the Widget build()
        user_json = value;
        name = value[0].name;
        phone_number = value[0].phone;
      });
    });
}

in RenderProfileView class body add loader until async data load in ProfilePage widget for that do like this.

body: user_json == null ? const Center(child: CircularProgressIndicator())  : ProfilePage(name, widget.email, user_json[0]['rollno'], phone_number, user_json[0].batch, user_json[0].dept, user_json[0].gender, ["a", "b", "c", "d"], user_json[0].photoImgLink, edit_or_display_name, edit_or_display_phone_number, error_message),
  • Related