skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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"]); // 👈 You are creating new variable mydata
          
           mydata = (value.data()?['uname'] ?? "Default userName"); //👈 Replace the above line by this
    
           print(mydata)  // Print the data once so that you know if the correct data is fetched.
      });
      notifyListeners();
    }
    

    So now you can use it as Text(providerdemo.mydata)


    Edit

    Create Notifier

    class UsersState extends ChangeNotifier{
    String userName = '';
    
    void getName(){
      FirebaseFirestore.instance
          .collection("Users")
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .get()
          .then((value) {
             userName = (value.data()?[' uname'] ?? "Default userName");
             print(userName)  // Print the data once so that you know if the correct data is fetched.
        });
        notifyListeners();
    }
    
    

    Change your main.dart file to contain Notifier

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return ChangeNotifierProvider<UserState>(
          create: (context)=> UsersState(),
          child:MaterialApp(
            home: myHomePage(),
          )
        );
      }
    }
    

    Screen where you want to display the name

    class ProfileScreen extends StatelessWidget {
      const ProfileScreen({super.key});
    
      @override
      Widget build(BuildContext context) {
        Provider.of<UserState>(context, listen: false).getName();
        final String name = Provider.of<UsersState>(context).userName;
    
        return Center(
          child: Text(name),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search