Home > Enterprise >  Flutter: Error "The getter 'mydata' isn't defined for the type 'providerdem
Flutter: Error "The getter 'mydata' isn't defined for the type 'providerdem

Time:01-01

I've defined a variable myvalue for accessing the document field from cloud firestore in Provider class providerdemo .But when I am trying to access it shows error The getter 'mydata' isn't defined for the type 'providerdemo'. .What's wrong in my code ?

providerdemo.dart

class providerdemo with ChangeNotifier {
  static String? mydata;
  final userData = FirebaseFirestore.instance
      .collection("Users")
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .get()
      .then((value) {
     mydata =(value.data()?['uname'] ?? "Default userName");
}

Below is the class where I'm trying to access the value into Text() widget;

class _testState extends State<test> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     body: Text(Provider.of<providerdemo>(context).mydata ?? "default"),
    );
  }
}

CodePudding user response:

You didn't declare the variable in the class scope, only in the function scope. So what you have to do, is declare the variable like this:

class providerdemo with ChangeNotifier {
    final mydata;

    void setMydata(final data) {
        mydata = data;
        notifyListeners();
    }
}

And for the best logic separation, you should create another file with for example a Cloud class, where you will write all the firebase related functions. Then when you initialise your app, you should call the following function like this: final data = Cloud.getMydata();, and use the setMydata function from your provider file in your UI code to update the variable.

class Cloud {
    static dynamic getMydata() async {
        return await FirebaseFirestore.instance
            .collection("Users")
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .get();
    }
}

(Didn't test the code) Also, please use CamelCase for class names.

CodePudding user response:

You are getting the error The getter 'mydata' isn't defined for the type 'providerdemo' because you have not defined the function mydata in the providerdemo class


Further there are two problems:

  1. You are defining the mydata twice, because of which it is not updating ,
  2. It is not value.data() ?? ["uname"] it is value.data()["uname"] ?? "Default userName"
class providerdemo with ChangeNotifier {
  static String mydata;
  final userData = FirebaseFirestore.instance
      .collection("Users")
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .get()
      .then((value) {

    // var mydata = (value.data() ?? ["uname"]); //            
  • Related