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
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:
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.(Didn’t test the code)
Also, please use CamelCase for class names.
You are getting the error
The getter 'mydata' isn't defined for the type 'providerdemo'
because you have not defined the functionmydata
in theproviderdemo
classFurther there are two problems:
mydata
twice, because of which it is not updating ,value.data() ?? ["uname"]
it isvalue.data()["uname"] ?? "Default userName"
So now you can use it as
Text(providerdemo.mydata)
Edit
Create Notifier
Change your main.dart file to contain
Notifier
Screen where you want to display the name