Flutter Navigator push data from firebase - firebase

We are trying to get data from firebase which we have currently being rendered within a grid view, but I want to be able to click on the item within the grid view and read more about it.
This is what I have so far and the error I am getting in VS
The argument type 'DocumentSnapshot' can't be assigned to the parameter type 'Merchant'.
HomeScreen
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:paylaterapp/screens/GridMerchantDetails.dart';
Future<void> main() async {
final FirebaseApp app = await FirebaseApp.configure(
name: 'BNPL',
options: const FirebaseOptions(
googleAppID: '***',
gcmSenderID: '***',
apiKey: '***',
projectID: '***',
),
);
final Firestore firestore = Firestore(app: app);
await firestore.settings(timestampsInSnapshotsEnabled: true);
}
class HomeScreen extends StatelessWidget {
HomeScreen(this.firestore);
final Firestore firestore;
CollectionReference get merchants => firestore.collection("merchants");
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stores'),
),
body: _gridView(),
);
}
Widget _gridView() {
return StreamBuilder<QuerySnapshot>(
stream: firestore.collection('merchants').orderBy('name', descending: false).snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return const Text('Loading...');
final int merchantCount = snapshot.data.documents.length;
return GridView.builder(
scrollDirection: Axis.vertical,
itemCount: merchantCount,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemBuilder: (_, int index) {
final DocumentSnapshot document = snapshot.data.documents[index];
final dynamic logo = document['logo_url'], mainImage = document['main_image_url'];
return
CupertinoButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GridMerchantDetails(document),
),
);
},
child: (
Container(
height: 300,
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey,
image: DecorationImage(
image: new NetworkImage(mainImage != null ? mainImage.toString() : 'https://images.unsplash.com/photo-1446844805183-9f5af45f89ee',
)
)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Image.network(logo != null ? logo.toString() : 'https://images.unsplash.com/photo-1446844805183-9f5af45f89ee',
width: 220,
fit: BoxFit.fill,
)
]
)
)
)
);
},
);
},
);
}
}
class GridMerchantDetails extends StatelessWidget {
final Merchant merchant;
GridMerchantDetails(this.merchant);
#override
Widget build(BuildContext context) {
return Scaffold(
primary: true,
appBar: AppBar(
title: Text(merchant.name),
),
backgroundColor: Colors.deepPurpleAccent,
body: ListView(
children: <Widget>[
HeaderBanner(this.merchant),
Container(
padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 20.0),
child: Text(
merchant.desc,
style: TextStyle(
fontSize: 13.0,
color: Colors.white,
),
),
),
],
),
);
}
}

Related

How to get userdata from firestore when refreshing the browser?

I have a Flutter web application where I sign in and navigate to a homepage.
Here I display the name of the user and that is working fine until I refresh my browser.
When I refresh my browser it returns a null value, but when I navigate to another page and back again I retrieve the users name. So I hoping there is another way to do this so I get my users name after refreshing the browser.
When I try to retrieve the users email from FirebaseAuth instead of the usersname from Firestore it works fine when refreshing the browser. So I think it has something to do with how I retrieve it from Firestore.
Here is some of my code:
Main.dart
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
final FirebaseAuth auth = FirebaseAuth.instance;
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot)
{
if (snapshot.hasError) {
return (MaterialApp(
home: UserLoginPage(
),
));
}
if (snapshot.connectionState == ConnectionState.done) {
print('CONNECTED');
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (BuildContext context, snapshot) {
return MaterialApp(
home: snapshot.hasData && snapshot.data != null
? const UserHomePage()
: const UserLoginPage(),
routes: {
UserLoginPage.id: (context) => const UserLoginPage(),
UserHomePage.id: (context) => const UserHomePage(),
},
debugShowCheckedModeBanner: false,
);
}
);
}
return Column();
});
}
}
HomePage
class _UserHomePageState extends State<UserHomePage> {
final scaffoldkey = GlobalKey<ScaffoldState>();
User? user = FirebaseAuth.instance.currentUser;
Future _getUserData() async {
await FirebaseFirestore.instance.collection('users').doc(user?.uid)
.get()
.then((snapshot) async {
if (snapshot.exists) {
setState(() {
name = snapshot.data()!['Navn'];
print(name!);
});
}
});
}
DateTime now = DateTime.now();
#override
void initState() {
super.initState();
_getUserData();
}
//String
String? name = '';
String? formattedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
#override
Widget build(BuildContext context) {
var appBarHeight = kToolbarHeight;
return Scaffold(
key: scaffoldkey,
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: const Color.fromRGBO(119, 221, 167, 1),
title: const Text(
'Test',
style: TextStyle(
fontFamily: 'Poppins',
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
),
backgroundColor: Colors.white,
drawer: Container(
padding: EdgeInsets.only(top: appBarHeight + 1),
child: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(name!),
),
const SizedBox(
height: 10,
),
],
),
),
),
body: SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(
height: 20,
),
Text('Hei, $name!',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),),
],
),
),
));
}
}

FirebaseFirestore - Snapshot with 'where'

Does anyone have a example for using the 'where' in the snapshot for FirebaseFirestore?
As I want to listen to the documents where one of the fields are equal to a specific email.
This I want then to use to update my Scaffold to display the current settings.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Test2 extends StatelessWidget {
const Test2({Key? key}) : super(key: key);
static const String id = 'test_2';
final TextEditingController _deviceName = TextEditingController();
final TextEditingController _onHour = TextEditingController();
#override
var firebaseUser = FirebaseAuth.instance.currentUser?.email;
final CollectionReference _device =
FirebaseFirestore.instance.collection('devices').where('email', isEqualTo: '$firebaseUser') as CollectionReference<Object?>;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(leading: null,
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.close))
],
title: const Text('Device Selection page'),),
body: StreamBuilder(
stream: _device.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (streamSnapshot.hasData) {
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (context, index) {
final DocumentSnapshot documentSnapshot = streamSnapshot.data!
.docs[index];
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
title: Text(documentSnapshot['deviceName']),
subtitle: Text(documentSnapshot['startHour'].toString()),
trailing: SizedBox(
width: 100,
child: Row(
children: [IconButton(
onPressed: () {}, icon: const Icon(Icons.edit)),
IconButton(onPressed: () {},
icon: const Icon(Icons.delete))
],
),
),
),
);
},);
};
return Container(
child: Row(
children: [Text('Test')],
),
);
},
)
);
}
}

Firebase : Why appearing [clound_firestore/permission-denied] for my firestore

I know there is a lot of similar posts, but I still cannot find my own answer for my issue. Since I want to get the data from firebase without pressing the button and diretly can get the data from it, therefore I have used the StreamBuilder for my coding but I still get this error. Is this is my firestore database or realtime database permission get any wrong?
--Issue warning--
Below are my coding:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:profile_staff/edit_profile_page.dart';
import 'package:profile_staff/profile_widget.dart';
import 'package:profile_staff/user.dart';
import 'package:profile_staff/user_preferences.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final Stream<QuerySnapshot> users =
FirebaseFirestore.instance.collection('users').snapshots();
TextEditingController _controller = TextEditingController();
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final user = UserPreferences.myUser;
return Scaffold(
appBar: AppBar(
leading: new IconButton(
onPressed: () {}, icon: new Icon(Icons.arrow_back_ios_sharp)),
title: Center(
child: Text(
'My Profile',
style: TextStyle(color: Colors.white),
),
),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => EditProfilePage()),
);
},
icon: new Icon(Icons.create_outlined))
],
backgroundColor: Colors.green,
shadowColor: Colors.white,
elevation: 3,
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Read Data',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
Container(
height: 250,
padding: const EdgeInsets.symmetric(vertical: 20),
child: StreamBuilder<QuerySnapshot>(
stream: users,
builder: (
BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot,
) {
// if (!snapshot.hasData) {
// return Text('error404');
// }
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading');
}
final data = snapshot.requireData;
return ListView.builder(
itemCount: data.size,
itemBuilder: (context, index) {
return Text(
'My name is ${data.docs[index]['name']} and I am ${data.docs[index]['age']}');
},
);
},
))
],
),
}
My Firestore Database:
My Realtime Database:
enter image description here
enter image description here
I was facing same issue.Forgot to deploy/upload new rules

How to make a streambuilder return data in other screens

I am new in Flutter, I have a question about an implementation I want to add my app, I would appreciate your answers, let me know if you need me to give you more information.
I hope, this is clear.
Here is the implementation I want to add my app...
I have a streambuilder in my home page(see below code implementing a container that has a streambuilder as a child) that gets data from firebase(the data is users information) and returns a Listview.builder that builds a list of containers with data like name and email(for each user) in my home screen...now, how can I replace the listView.builder and instead of having those users in a listview.builder, I actually want those users information to be saved one by one into different screens(like creating a user profile for each user).
This is the streambuilder:
Container(
///this is a regular streambuilder as a child of a container
child: StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
///THIS IS THE LISTVIEW.BUILDER
return ListView.builder(
padding: EdgeInsets.all(10.0),
///These are some methods that build the containers list with the users information
itemBuilder: (context, index) =>
buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
COMPLETE CODE FOR MY HOMEPAGE
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:jobly10/chat_implementation/settings.dart';
import 'chat.dart';
import 'const.dart';
import '../main.dart';
class HomeListViewUsers extends StatefulWidget {
final String currentUserId;
HomeListViewUsers({Key key, this.currentUserId}) : super(key: key);
#override
State createState() => HomeListViewUsersState(currentUserId: currentUserId);
}
class HomeListViewUsersState extends State<HomeListViewUsers> {
HomeListViewUsersState({Key key, #required this.currentUserId});
final String currentUserId;
final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final GoogleSignIn googleSignIn = GoogleSignIn();
bool isLoading = false;
List<Choice> choices = const <Choice>[
const Choice(title: 'Settings', icon: Icons.settings),
const Choice(title: 'Log out', icon: Icons.exit_to_app),
];
#override
void initState() {
super.initState();
registerNotification();
configLocalNotification();
}
void registerNotification() {
firebaseMessaging.requestNotificationPermissions();
firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
firebaseMessaging.getToken().then((token) {
print('token: $token');
Firestore.instance
.collection('users')
.document(currentUserId)
.updateData({'pushToken': token});
}).catchError((err) {
Fluttertoast.showToast(msg: err.message.toString());
});
}
void configLocalNotification() {
var initializationSettingsAndroid =
new AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
void onItemMenuPress(Choice choice) {
if (choice.title == 'Log out') {
handleSignOut();
} else {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Settings()));
}
}
void showNotification(message) async {
var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
Platform.isAndroid
? 'com.dfa.flutterchatdemo'
: 'com.duytq.flutterchatdemo',
'Flutter chat demo',
'your channel description',
playSound: true,
enableVibration: true,
importance: Importance.Max,
priority: Priority.High,
);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
print(message);
await flutterLocalNotificationsPlugin.show(0, message['title'].toString(),
message['body'].toString(), platformChannelSpecifics,
payload: json.encode(message));
}
Future<Null> handleSignOut() async {
this.setState(() {
isLoading = true;
});
await FirebaseAuth.instance.signOut();
await googleSignIn.disconnect();
await googleSignIn.signOut();
this.setState(() {
isLoading = false;
});
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => MyApp()),
(Route<dynamic> route) => false);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Chat Screen',
style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: WillPopScope(
child: Stack(
children: <Widget>[
// List
Container(
///here the chats users are called
child: StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
///THIS IS THE LISTVIEW.BUILDER
return ListView.builder(
padding: EdgeInsets.all(10.0),
///These are some methods that build the containers list with the users information
itemBuilder: (context, index) =>
buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
// Loading
Positioned(
child: isLoading
? Container(
child: Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(themeColor)),
),
color: Colors.white.withOpacity(0.8),
)
: Container(),
)
],
),
// onWillPop: onBackPress,
),
);
}
Widget buildItem(BuildContext context, DocumentSnapshot document) {
if (document['id'] == currentUserId) {
return Container();
} else {
return Container(
child: FlatButton(
child: Row(
children: <Widget>[
Material(
child: document['profileImageUrl-'] != null
? CachedNetworkImage(
placeholder: (context, url) => Container(
child: CircularProgressIndicator(
strokeWidth: 1.0,
valueColor:
AlwaysStoppedAnimation<Color>(themeColor),
),
width: 50.0,
height: 50.0,
padding: EdgeInsets.all(15.0),
),
//i just cange this
imageUrl: document['profileImageUrl'],
width: 50.0,
height: 50.0,
fit: BoxFit.cover,
)
: Icon(
Icons.account_circle,
size: 50.0,
color: greyColor,
),
borderRadius: BorderRadius.all(Radius.circular(25.0)),
clipBehavior: Clip.hardEdge,
),
Flexible(
child: Container(
child: Column(
children: <Widget>[
Container(
child: Text(
'Name: ${document['nickname']}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
),
Container(
child: Text(
'email: ${document['email']}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
),
Container(
child: Text(
'About me: ${document['aboutMe'] ?? 'Not available'}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
)
],
),
margin: EdgeInsets.only(left: 20.0),
),
),
],
),
onPressed: () {
///here is the flat button to go to messages
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: document.documentID,
peerAvatar: document['photoUrl'],
),
),
);
},
color: greyColor2,
padding: EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
),
margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
);
}
}
}
class Choice {
const Choice({this.title, this.icon});
final String title;
final IconData icon;
}
If you want each item in the ListView.builder to be 'tappable' and send you to a profile screen containing the tapped user's information, try wrapping each ListView element in a GestureDetector:
return ListView.builder(
padding: EdgeInsets.all(10.0),
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
GestureDetector(
onTap: Navigator.push(context,
MaterialPageRoute(builder: (context) => UserProfile(user_name, user_age, user_etc)),);
child: buildItem(context, snapshot.data.documents[index])
),
);
You can pass info from your Stream into a newly made UserProfile (or something to that effect) page, which is navigated to by tapping on either of the ListView panels.
Alternatively, in your buildItem widget definition, you can return a GestureDetector (which will wrap your current Container) instead and place the onTap logic in there.

Getting data from cloud firestore onto a listview in flutter

I am trying to pull data from a firebase cloud firestore collection (events) onto a list view, I’m not sure if I am implementing this correctly, when I run the app I get the error 'MappedListIterable' is not a subtype of type 'Widget'. This is my first time working with firebase cloud firestore and I could really use some help in better understanding this error.
This is where the list view is being initialized:
import 'package:flutter/material.dart';
import 'package:rallie_app/utils/event_summary.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class HomeList extends StatelessWidget {
Firestore db = Firestore.instance;
#override
Widget build(BuildContext context) {
return Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('events').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
// count of events
final int eventCount = snapshot.data.documents.length;
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState){
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
return new ListView.builder(
itemCount: eventCount ,
itemBuilder: (context, index) {
final DocumentSnapshot document = snapshot.data.documents[index];
return new EventSummary(document);
}
);
}
})
);
}
}
These are the list view items I wish to build :
import 'package:flutter/material.dart';
import 'package:rallie_app/model/events.dart';
import 'package:rallie_app/ui/detail/detail_page.dart';
import 'package:rallie_app/services/firestore_service.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
class EventSummary extends StatefulWidget {
//TODO: Event summary constructor with event model class initialized in it
final DocumentSnapshot event;
EventSummary(this.event);
#override
_EventSummaryState createState() => _EventSummaryState();
}
class _EventSummaryState extends State<EventSummary> {
#override
Widget build(BuildContext context) {
final userThumbnail = new Container(
margin: EdgeInsets.symmetric(vertical: 16.0),
alignment: FractionalOffset.centerLeft,
child: Hero(
tag: "user-image-${widget.event.data['id']}",
child: CircleAvatar(
backgroundImage: AssetImage(widget.event['event_poster_image']),
// backgroundColor: Colors.white,
maxRadius: 40.0,
),
),
);
final eventCardContent = Container(
margin: new EdgeInsets.only(left: 46.0),
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: new Color(0xFFFFFFFF),
borderRadius: new BorderRadius.circular(8.0),
image: DecorationImage(
image: AssetImage(widget.event.data['event_image']),
fit: BoxFit.fill,
),
),
);
Widget _eventValue(){
return Column(
children: <Widget>[
Container(
height: 150.0,
margin: const EdgeInsets.symmetric(
vertical: 16.0,
horizontal: 24.0,
),
child: new Stack(
children: <Widget>[
eventCardContent,
userThumbnail,
],
),
),
Container(
margin: const EdgeInsets.only(left: 70.0, bottom: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.event.data['event_name'],
textAlign: TextAlign.start,
),
Row(
//crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.event.data['event_date'],
textAlign: TextAlign.start,
),
SizedBox(
width: 110,
),
IconButton(
icon: Icon(Icons.share),
splashColor: Colors.orange,
tooltip: 'Share button',
onPressed: () =>
debugPrint('Share btn tapped'),
)
],
),
Text(
widget.event.data['event_attending'],
textAlign: TextAlign.start,
),
],
),
)
],
);
}
return new GestureDetector(
onTap: () => Navigator.of(context).push(
new PageRouteBuilder(
pageBuilder: (_, __, ___) => new DetailPage(widget.event.data['id']),
transitionsBuilder:
(context, animation, secondaryAnimation, child) =>
new FadeTransition(opacity: animation, child: child),
),
),
child: StreamBuilder(
stream: Firestore.instance.collection('events').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading data... Please wait');
return snapshot.data.documents.map(
(document) => _eventValue()
);
}),
);
}
}
In Your Code - Edit - widget.event['id'] to - widget.event.data['id'] & So On same with Other Places where you have Snapshot variable used...
As Per Documentation - DocumentSnapshot
A DocumentSnapshot contains data read from a document in your Cloud
Firestore database. The data can be extracted with .data()
widget.event is - DocumentSnapshot & to read the data you need to use .data Method.
Also the Error you are Getting is of Code :
child: StreamBuilder(
stream: Firestore.instance.collection('events').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading data... Please wait');
return snapshot.data.documents.map(
(document) => Column(
......
Here Builder is Expecting a Widget as a return value not 'MappedListIterable' -
snapshot.data.documents.map(
(document) // is Wrong return value for StreamBuilder.
You Need Modify Your Code to return a widget here.

Resources