In my code I tried to fecth age filed from users table using userID. Structure of database.
childPrivateDetails is a subcollection of user table
**I want to fetch age from this table how to do that and pass when click next button should pass the age to "void ageCa()" method **
code
class _GuideLineScreenState extends State<GuideLineScreen> {
Future<void> getAge() async {
final sp = context.read<SignInProvider>();
Future<void> getAge() async {
final path = 'users/${sp.uid}/childPrivateDetails/${sp.uid}';
final reference = FirebaseFirestore.instance.doc(path);
final age = await reference.get().then((value) => value.get('age'));
print('age is: $age');
}
}
next button code
SizedBox(
width: 160.0,
height: 35.0,
child: ElevatedButton(
style: ButtonStyle(
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: const BorderSide(
color: Colors.blueAccent,
),
),
),
),
onPressed: () {
ageCa();
},
child: const Text(
'next',
style: TextStyle(
color: Colors.white,
),
),
),
),
void ageCa() code
void ageCa() {
String age = age;
final data = age.split(",");
final List<int> numbers =
data.map((e) => int.parse(e.replaceAll(RegExp('[^0-9]'), ''))).toList();
//format "Years: 2, Months: 00, Days: 00"; only work on this format
Duration ageDuration =
Duration(days: numbers[0] * 365 numbers[1] * 30 numbers[2]);
if (ageDuration >= const Duration(days: 2 * 288)) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const LoginScreen()),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomeScreen(),
));
}
}
For this, I didn't use model path image
I added print($age); at the Widget build(BuildContext context) {
CodePudding user response:
Try the following code:
FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
future: FirebaseFirestore.instance
.collection("users")
.doc(sp.uid)
.collection("childPrivateDetails")
.doc(sp.uid)
.get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return Text(snapshot.data.data()!["age"]);
},
),
CodePudding user response:
Use the get()
method to fetch single field like so:
Future<void> getAge() async {
final uid = IZf3qxWtmxcWF6oXh1nbB8SK4az2
final path = 'users/$uid/childPrivateDetails/$uid';
final reference = FirebaseFirestore.instance.doc(path);
final age = await reference.get().then((value) => value.get('age'));
print('age is: $age');
}
CodePudding user response:
As far as I know, firebase document snapshoot have just function .data()
not an .data.data()
Your error is highlighting that .data()
not exists, and it is because .data
before .data()
is a function not a variable. I might be wrong, I'm not a swift programmer. Give me a call if I'm wrong and your snapshot returns something like variable .data
.