NoSuchMethodError : ‘[]’ in flutter

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

1

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.

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.

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}');
      }
    },
  )

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật