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"),
);
}
}
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:
mydata
twice, because of which it is not updating ,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)
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();
}
Notifier
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<UserState>(
create: (context)=> UsersState(),
child:MaterialApp(
home: myHomePage(),
)
);
}
}
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),
);
}
}