How to put different images and redirect users to other pages in ListView Builder? - firebase

Writing a code in Flutter right now and I can display a database with ListView.
However, I want to put pictures of the destination according to its location so I was wondering how to put different images for each different item? The same goes for the onTap void callback function as well. I want each list item to go to different pages where further details of the destination is given.
Code:
class _DispDestState extends State<DispDest> {
List<AllDestinations> destinationsList = [];
#override
void initState() {
super.initState();
DatabaseReference referenceAllCourses = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
referenceAllCourses.once().then(((DataSnapshot dataSnapshot) {
destinationsList.clear();
var keys = dataSnapshot.value.keys;
var values = dataSnapshot.value;
for (var key in keys) {
AllDestinations allDestinations = new AllDestinations(
values[key]['name'],
values[key]['description'],
values[key]['category'],
);
if (allDestinations.category.toString() == 'Destination')
destinationsList.add(allDestinations);
}
setState(() {});
}));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.fromLTRB(20, 5, 20, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Come and Explore",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 14,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w500,
letterSpacing: 0.5,
),
),
SizedBox(height: 15),
Expanded(
child: SingleChildScrollView(
child: Column(children: <Widget>[
destinationsList.length == 0
? Center(
child: Text(
"Loading...",
style: TextStyle(fontSize: 15),
))
: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: destinationsList.length,
itemBuilder: (_, index) {
return DestinationCard(
title: destinationsList[index].destname,
onTap: () {},
img: 'assets/icons/temp.png');
})
]),
),
),
])));
}
}
class DestinationCard extends StatelessWidget {
final String title, img;
final VoidCallback onTap;
const DestinationCard({
Key? key,
required this.title,
required this.img,
required this.onTap,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: 400,
height: 190,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(15, 155, 0, 0),
width: 350,
height: 190,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: AssetImage(img), fit: BoxFit.cover),
),
child: Text(
title,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
);
}
}

You should add a parameter named imagePath to AllDestinations class. So when you use DestinationCard in ListView.builder, you can add:
return DestinationCard(
title: destinationsList[index].destname,
onTap: () {},
img: destinationsList[index].imagePath,
);

Related

How to change the border colour of a card upon tapping it wrapped in listview.builder in flutter?

I am fetching certain details from firebase and showing them in the form of card, with the help of ListView.Builder. Now, upon tapping a specific card I want to change its border colour to green. I have tried using the flag variable in the setState but it sets the border colour for every card to green. Someone pls have a look at the code I've pasted, and let me know what should be done.This is the image of the UI
Thank You:)
StreamBuilder<QuerySnapshot>(
stream: collectionTests.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
final myDocs = snapshot.data!.docs;
try {
return ListView.builder(
itemCount: myDocs.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(17, 11, 17, 11),
child: InkWell(
onTap: () {},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: const BorderSide(
color: Colors.white,
),
),
child: ListTile(
contentPadding: const EdgeInsets.all(8),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
myDocs[index]['name'],
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Card(
color: Colors.indigo,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
myDocs[index]['price'],
style: const TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontSize: 20,
),
),
),
)
],
),
subtitle: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 12, 8),
child: Text(
myDocs[index]['description'],
style: const TextStyle(
fontSize: 18,
),
),
),
),
),
),
);
},
);
} catch (e) {
return const Center(
child: Card(
child: Text(
'Something went wrong, please check your connection',
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}
}
},
),
Extract your widget into a new stateful class and call the class inside the ListView.
main.dart
import 'package:flutter/material.dart';
import 'package:stackoverflow/custom_card.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, i){
return CustomCard();
},
),
),
);
}
}
custom_card.dart
import 'package:flutter/material.dart';
class CustomCard extends StatefulWidget {
const CustomCard({Key? key}) : super(key: key);
#override
_CustomCardState createState() => _CustomCardState();
}
class _CustomCardState extends State<CustomCard> {
Color borderColor = Colors.black;
#override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
height: 100,
child: GestureDetector(
onTap: (){
setState(() {
borderColor = Colors.green;
});
},
child: Card(
color: borderColor,
),
),
);
}
}
Firstly, you need to define a list that contains bool variables out of build method. These variables will decide whether the border of relevant card is white or green.
List<bool> bordersColors = [];
Then in your listview like this;
return ListView.builder(
itemCount: myDocs.length,
itemBuilder: (context, index) {
bordersColors.add(false);
return Padding(
padding: const EdgeInsets.fromLTRB(17, 11, 17, 11),
child: InkWell(
onTap: () {
setState((){
bordersColors[index] = true;
})
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: const BorderSide(
color: bordersColors[index] ? Colors.green : Colors.white,
),
),
child: ListTile(
contentPadding: const EdgeInsets.all(8),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
myDocs[index]['name'],
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
Card(
color: Colors.indigo,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
myDocs[index]['price'],
style: const TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontSize: 20,
),
),
),
)
],
),
subtitle: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 12, 8),
child: Text(
myDocs[index]['description'],
style: const TextStyle(
fontSize: 18,
),
),
),
),
),
),
);
},
);
} catch (e) {
return const Center(
child: Card(
child: Text(
'Something went wrong, please check your connection',
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);

How to get the checkbox value for each element in the ListView.builder?

please help me, ive been trying a lot of tutorials but i still failed to checked one checkbox with its value in the ListView.builder.
Below is my code that I supposed to add checkbox with its own value. Each card contain the picture and its description, and the user supposely have to select the picture that they need. With that, the image checked should be store in the firebase database.
//import 'dart:html';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/data/user_model.dart';
import 'package:smartconstructionreport/screens/image_details.dart';
import 'package:smartconstructionreport/screens/project_screen.dart';
import 'package:smartconstructionreport/theme.dart';
import 'package:intl/intl.dart';
import 'dart:ui';
import 'dart:io';
class WorkPerformedForm extends StatefulWidget {
final Project project;
final String reportID ;
final int itemIndex;
final String albumid;
const WorkPerformedForm({this.project, #required this.reportID, this.albumid, this.itemIndex});
#override
_WorkPerformedFormState createState() => _WorkPerformedFormState();
}
class _WorkPerformedFormState extends State<WorkPerformedForm> {
FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
User user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
final Ref = FirebaseFirestore.instance
.collection("images")
.doc('photoid')
.snapshots();
ImageDetails date;
DateTime now = DateTime.now();
#override
void initState() {
super.initState();
FirebaseFirestore.instance
.collection("user")
.doc(user.uid)
.get()
.then((value) {
this.loggedInUser = UserModel.fromMap(value.data());
// name = value.data()['name'];
setState(() {});
//getAlbumID();
});
//checklist.forEach((element) => checkboxStatus.add(false));
}
List<bool> checkboxStatus = [];
bool _checked = false;
#override
Widget build(BuildContext context) {
String _formatteddate = new DateFormat.yMMMd().format(now).toString();
double width = MediaQuery.of(context).size.width * 0.5;
return Scaffold(
appBar: new AppBar(
title: FittedBox(
fit: BoxFit.fill,
child: Text(
'Work Performed',
style: TextStyle(
fontSize: 25,
color: Color(0xFF222B45),
fontFamily: 'Poppins',
fontWeight: FontWeight.w700,
),
),
),
centerTitle: true,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios, color: kPrimaryColor),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return ProjectScreen(project: widget.project,);
}),
);
},
),
backgroundColor: Colors.transparent,
elevation: 0,
),
body: StreamBuilder<QuerySnapshot>(
stream: _firebaseFirestore
.collection("album")
.doc(widget.albumid)
.collection("images")
.where("photographer", isEqualTo: this.loggedInUser.name)
//.where("dateUploaded", isEqualTo: _formatteddate)
.orderBy('dateUploaded', descending: true)
.snapshots(),
// ignore: missing_return
builder: (BuildContext context, snapshot) {
return snapshot.connectionState == ConnectionState.waiting
? Center(child: CircularProgressIndicator())
: snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, index){
return GestureDetector(
onTap: (){
//print(checkboxStatus.length);
print(snapshot.data.docs[index].get('url'));
showDialogFunc(context, snapshot.data.docs[index].get('url'), snapshot.data.docs[index].get('stageOfWork'), snapshot.data.docs[index].get('description'));
},
child: Card(
child: Row(
children: <Widget>[
Container(
width: 100,
height: 100,
child: ImageView(
imagePath: snapshot.data.docs[index].get('url'),
index: index,
photoid: snapshot.data.docs[index].get('photoid'),
albumid: widget.albumid,
project: widget.project),
),
Padding(padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
snapshot.data.docs[index].get('stageOfWork') !=null
?Text(snapshot.data.docs[index].get('stageOfWork'),
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontWeight: FontWeight.bold,
)
): Text(
"None",
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontWeight: FontWeight.bold,
)),
SizedBox( height: 10,),
Container(
width: width,
child: snapshot.data.docs[index].get('description') != null
?Text(
snapshot.data.docs[index].get('description'),
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontStyle: FontStyle.italic,
),
): Text(
"No description yet",
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontStyle: FontStyle.italic,
)),
),
],
),),
Padding(padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Checkbox(
value: _checked,
onChanged: (value) {
print(checkboxStatus.length);
setState((() {
_checked =
!_checked;
}));
},
checkColor: Colors.white,
)
],
),
),
],
),
),
);
})
: Container();
},
),
);
}
}
class ImageView extends StatelessWidget {
final String imagePath;
final int index;
final String photoid;
final String albumid;
final Project project;
ImageView(
{#required this.imagePath,
#required this.index,
#required this.photoid,
#required this.albumid,
#required this.project});
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Hero(
tag: 'logo$index',
child: Image.network(imagePath,
fit: BoxFit.cover,),
),
onTap: () {
});
}
}
showDialogFunc(context,String url, String sow, String decs){
return showDialog(
context:context,
builder: (context){
return Center(
child: Material(
type: MaterialType.transparency,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
),
padding: EdgeInsets.all(15),
width: MediaQuery.of(context).size.width *0.7,
height: 320,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(5),
child: Image.network(url,
width: 200,
height: 200,),
),
SizedBox(
height:20
),
sow!=null?
Text(
sow,
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontWeight: FontWeight.bold,
)
):Text(
"None",
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontStyle: FontStyle.italic,
)),
SizedBox(
height:10
),
decs != null?
Text(
decs,
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontStyle: FontStyle.italic,
),
textAlign: TextAlign.center,
): Text(
"No description yet",
maxLines: 3,
style: TextStyle(
fontSize: 15,
fontFamily: 'Poppin',
fontStyle: FontStyle.italic,
)),
],
),
),
),
);
}
);
}
here is the interface
Interface
You need to save the states of each checkbox in similar things like your list.
I would create a Map<String, bool> and update/get the values of each entry. The strings would be the doc ids and the bool the checkbox state concerning the doc id

Error is not showing after scanning a item thats not on the firestore database

I did this personal project of mine where a barcode scanner would scan for data inside firestore database. I have this problem when I scanned a barcode thats not on the database it wont show the error message is just shows a empty scan item container which I made. Let me know if someone can figure why. I tried everything still couldnt fix it.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("products")
.where("barcode", isEqualTo: '$barcodeScanRes')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Dialog(
child: Container(
height: 300,
child: Text('Product Not Found'),
),
);
} else {
return Dialog(
child: Container(
height: 350,
child: Column(children: [
Container(
height: 350,
width: 165,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data!.docs[index];
return ScanCard(products: products);
},
)),
]),
),
);
#Scan Card
class ScanCard extends StatelessWidget {
const ScanCard({
Key? key,
required this.products,
}) : super(key: key);
final DocumentSnapshot products;
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser;
String _userId = user!.uid;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(10.0),
height: 180,
width: 160,
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(16)),
child: Image.network(products['img']),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0 / 4),
child: Text(
products['name'],
style: TextStyle(
color: Colors.blueGrey,
fontSize: 18,
),
),
),
Column(
children: [
Text(
"Size: " + products['size'],
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.brown),
),
SizedBox(
width: 30,
),
],
),
Row(
children: [
Text(
"\tRs. " + products['price'],
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
SizedBox(
width: 40,
),
Icon(
Icons.add_shopping_cart,
color: Colors.black,
size: 25,
),
],
),
SizedBox(
width: 10,
),
SizedBox(
child: Padding(
padding: const EdgeInsets.all(10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
color: Colors.red,
child: Text(
"Add to cart",
style: TextStyle(color: Colors.white),
),
onPressed: () {
DocumentReference documentReference = FirebaseFirestore.instance
.collection('userData')
.doc(_userId)
.collection('cartData')
.doc();
documentReference.set({
'uid': FirebaseAuth.instance.currentUser!.uid,
'barcode': products['barcode'],
'img': products['img'],
'name': products['name'],
'size': products['size'],
'price': products['price'],
'id': documentReference.id
}).then((result) {
addToCartMessage(context).then((value) => {
Navigator.pop(context)
});
}).catchError((e) {
print(e);
});
},
),
),
)
],
);
}
}
The thing is you are showing Product not found based on the condition:- !snapshot.hasData but this conditon means that data is being fetched so at this time rather show a progress indicator.
And to handle when data is not present in backend then add another condition:- if(snapshot.data.docs.isEmpty) and here show your dialogbox of Product not found...
Final Code Snippet will look like:-
if (!snapshot.hasData)
return Center(child:CircularProgressIndicator));//or return a black container if you don't want to show anything while fetching data from firestore
else if (snapshot.data.docs.isEmpty) {
return Dialog(
child: Container(
height: 300,
child: Text('Product Not Found'),
),
);
} else {
return Dialog(
child: Container(
height: 350,
child: Column(children: [
Container(
height: 350,
width: 165,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data!.docs[index];
return ScanCard(products: products);
},
)),
]),
),
);
}

Cant Figure Out How To display Only the post details for the post I have clicked on

So I have this code here and I would like to display post details from firebase for the post which I have clicked on, but instead, it lists post details for every single post in the database one after another.
Can anyone help me figure out how I can make it so that when A post is clicked, details will show for only the post which was clicked, and not for all of the posts? Any help would be greatly appreciated, thank you.
The Info I would like to display on the post is
postTitle
postDesc
postAuthor
Here is what the firebase looks like
Code Here:
import 'package:tennis_event_app/services/crud.dart';
import 'package:tennis_event_app/views/create_blog.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
CrudMethods crudMethods = new CrudMethods();
QuerySnapshot? blogSnapshot;
#override
void initState() {
crudMethods.getData()?.then((result) {
blogSnapshot = result;
setState(() {});
});
super.initState();
}
Widget blogsList() {
return Container(
child: ListView.builder(
padding: EdgeInsets.only(top: 24),
itemCount: blogSnapshot!.docs.length,
itemBuilder: (context, index) {
return BlogTile(
author: blogSnapshot!.docs[index].get('author'),
title: blogSnapshot!.docs[index].get('title'),
desc: blogSnapshot!.docs[index].get('desc'),
imgUrl: blogSnapshot!.docs[index].get('imgUrl'),
);
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Flutter",
style: TextStyle(fontSize: 22),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
],
),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Container(
child: blogSnapshot != null
? blogsList()
: Container(
child: Center(
child: CircularProgressIndicator(),
))),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateBlog()));
},
),
);
}
}
class BlogTile extends StatelessWidget {
final String imgUrl, title, desc, author;
BlogTile(
{required this.author,
required this.desc,
required this.imgUrl,
required this.title});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 16, right: 16, left: 16),
child: Stack(
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(8)),
child: Image.network(
imgUrl,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
height: 170,
),
),
),
Container(
height: 170,
decoration: BoxDecoration(
color: Colors.black45.withOpacity(0.3),
borderRadius: BorderRadius.circular(6)),
),
Container(
height: 170,
width: MediaQuery.of(context).size.width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
title,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
SizedBox(height: 4),
Text(
'$desc',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w400),
),
SizedBox(
height: 4,
),
Text(author),
],
)),
Container(
child: SizedBox(
height: 170,
width: MediaQuery.of(context).size.width,
child: TextButton(
style: TextButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailPage()));
},
child: const Text(''),
),
),
),
],
),
);
}
}
class DetailPage extends StatefulWidget {
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
CrudMethods crudMethods = new CrudMethods();
QuerySnapshot? blogSnapshot;
#override
void initState() {
crudMethods.getData()?.then((result) {
blogSnapshot = result;
setState(() {});
});
super.initState();
}
Widget blogsList2() {
return Container(
child: ListView.builder(
padding: EdgeInsets.only(top: 24),
itemCount: blogSnapshot!.docs.length,
itemBuilder: (context, index) {
return PageContent(
postAuthor: blogSnapshot!.docs[index].get('postAuthor'),
postTitle: blogSnapshot!.docs[index].get('postTitle'),
postDesc: blogSnapshot!.docs[index].get('postDesc'),
imgUrl: blogSnapshot!.docs[index].get('imgUrl'),
);
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Flutter",
style: TextStyle(fontSize: 22),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
],
),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Container(
child: blogSnapshot != null
? blogsList2()
: Container(
child: Center(
child: CircularProgressIndicator(),
))),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateBlog()));
},
),
);
}
}
class PageContent extends StatelessWidget {
final String imgUrl, postTitle, postDesc, postAuthor;
PageContent(
{required this.postAuthor,
required this.postDesc,
required this.imgUrl,
required this.postTitle});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 16, right: 16, left: 16),
child: Card(
child: ListTile(
title: Text(
postTitle,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
subtitle: Text(
'$postDesc',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w400),
),
)
)
);
}
}
I also reference crud.dart in that code, so incase you need it, here it is:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:collection';
class CrudMethods {
Future<void> addData(blogData) async {
print(blogData);
FirebaseFirestore.instance
.collection("blogs")
.add(blogData)
.then((value) => print(value))
.catchError((e) {
print(e);
});
}
getData() async {
return await FirebaseFirestore.instance
.collection("blogs")
.orderBy("ts", descending: true)
.get();
}
}
Thank you again for any help!
First I would recommend to modelize your data in an object for exemple a class Article that is easier to serialize and manipulate.
Then instead of requesting another time the database you should save your data in a List<Article> for example then you only update this list on refresh from your main page. That way you don'y manipulate a QuerySnapshot or Future but just your list of objects.
Finally and to answer your question, you could simply pass the clicked item Article to your details page and only display its content. Because here, you have the same construction as your main page with the same request that is resent.
Usually you can build your route like that (adding a parameter to your details with the index you clicked on for example)
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailPage(article: _data[i])));
},
Here is an article on serialization from Flutter docs, it shows how to build your model with the toMap, toJson and fromJson methods.

How to get email of user from firebase in Text Widget

I want to write the User's email under the User's name in the Navigation drawer, but I cannot access the email in Text Widget
I used this code for fetching user email id from Firebase but unable to write inside Text
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
firebase_auth.FirebaseAuth firebaseAuth = firebase_auth.FirebaseAuth.instance;
Future<void> signOut() async {
await firebaseAuth.signOut();
}
dynamic user;
String userEmail;
getCurrentUserInfo() async {
user = await firebaseAuth.currentUser;
userEmail = user.email;
print(userEmail);
return userEmail;
}
static var chartdisplay;
bool isSwitched = true;
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Builder(
builder: (context) => IconButton(
icon: Image.asset(
"assets/images/menu.png",
),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
backgroundColor: const Color(0xffe8e5af),
elevation: 0,
centerTitle: false,
titleSpacing: 0,
),
drawer: new Drawer(
child: new ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 50, horizontal: 30),
color: const Color(0xffe8e5af),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
CircleAvatar(
radius: 46,
backgroundColor: Colors.white,
child: CircleAvatar(
backgroundImage: AssetImage('assets/images/avatar.jpg'),
radius: 40,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Nabia Salman',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.left,
),
Text(
//"${user.email}",
"nabia.salman99#gmail.com",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 9,
color: const Color(0xff000000),
),
textAlign: TextAlign.left,
),
],
),
],
),
),
This is how my screen looks like
Please help me out in finding the solution for this as I am new to Flutter
Thank you in advance

Resources