This is my working code:
final Stream<QuerySnapshot> products = FirebaseFirestore.instance
.collection('products')
.doc('men')
.collection('tshirts')
.snapshots();
This is the code I want but not working:
String val = 'tshirts';
final Stream<QuerySnapshot> products = FirebaseFirestore.instance
.collection('products')
.doc('men')
.collection(val)
.snapshots();
Error: The instance member 'val' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
The bellow code I am using in build widget to show database query results & working fine:
GridView.count(
physics: const BouncingScrollPhysics(),
crossAxisCount: 2,
childAspectRatio: 0.5,
mainAxisSpacing: 30,
crossAxisSpacing: 10,
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Visibility(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.bottomToTop,
child: const ProductView(productId: '3453245'),
));
},
child: Stack(
children: [
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('${data['img']}'),
fit: BoxFit.cover)),
),
Align(
alignment: Alignment.bottomLeft,
child: SizedBox(
height: 70,
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.only(
right: 18, top: 15, left: 5),
child: Text(
data['name'].toUpperCase(),
textAlign: TextAlign.left,
style: GoogleFonts.oswald(
color: Colors.black,
fontSize: 15,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: false,
),
),
Container(
margin: const EdgeInsets.only(left: 5),
child: Text(
'\u{20B9} ${data['price']}',
textAlign: TextAlign.left,
style: const TextStyle(
color: Colors.black,
fontSize: 14,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
)
],
),
).frosted(
blur: 7,
),
),
],
)),
visible: true,
);
}).toList(),
)
CodePudding user response:
You are trying to use val
before even initializing the class that is used.
You can only access it inside a method or the constructor, example:
@override
void initState() {
super.initState();
final Stream<QuerySnapshot> products = FirebaseFirestore.instance.collection('products').doc('men').collection(val).snapshots();
}