Flutter - Firebase Messaging Snackbar not showing - firebase

This is the problem: notification is received by the app both with app in foreground or background (or terminated) but the snackbar for notification when the app is used doesn't work. I'm new in flutter so maybe I did some huge mistake.
I am showing my code below. If you want more information just ask and thanks for the help!
// Import Package
import 'dart:io';
import 'package:app_gap_go/pages/admin/modifySingleMeeting.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/rendering.dart';
// Import Other Package
import 'package:provider/provider.dart';
// Import Pagine
import './pages/wrapper.dart';
import './pages/setting/settings.dart';
import './pages/riunioni/riunioni.dart';
import './pages/auth/register.dart';
import './pages/admin/pannelloAdmin.dart';
import './pages/admin/modifyMeetings.dart';
// Import Utility
import 'utility/themeData.dart';
// Import Services
import './services/authService.dart';
// Import Models
import './models/user.dart';
void main() {
// debugPaintSizeEnabled = true;
// debugPaintBaselinesEnabled = true;
// debugPaintPointersEnabled = true;
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final FirebaseMessaging _fcm = new FirebaseMessaging();
final Firestore _db = Firestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
GlobalKey<ScaffoldState> scaffoldState = new GlobalKey<ScaffoldState>();
// Request and save token
Future _saveDeviceToken() async {
String fcmToken = await _fcm.getToken();
FirebaseUser user = await _auth.currentUser();
if (fcmToken != null) {
var tokenRef = _db
.collection('utenti')
.document(user.uid)
.collection('tokens')
.document(fcmToken);
await tokenRef.setData({
'token': fcmToken,
'createdAt': FieldValue.serverTimestamp(),
'platform': Platform.operatingSystem,
});
}
}
#override
void initState() {
_fcm.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
final snackbar = SnackBar(
content: Text(message['notification']['title']),
action: SnackBarAction(
label: 'Go',
onPressed: () => null,
),
);
scaffoldState.currentState.showSnackBar(snackbar);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
);
if(Platform.isIOS) {
_fcm.onIosSettingsRegistered.listen((data) {
_saveDeviceToken();
});
_fcm.requestNotificationPermissions(IosNotificationSettings());
} else {
_saveDeviceToken();
}
_fcm.subscribeToTopic('meetings');
super.initState();
}
#override
Widget build(BuildContext context) {
return StreamProvider<User>.value(
key: scaffoldState,
value: AuthService().user,
child: MaterialApp(
title: "GapGo",
theme: themeApp,
routes: {
'/': (BuildContext context) => Wrapper(),
'/register': (BuildContext context) => Register(),
'/settings': (BuildContext context) => Settings(),
'/riunioni': (BuildContext context) => Riunioni(),
'/adminPanel': (BuildContext context) => PannelloAdmin(),
'/modifyMeetings': (BuildContext context) => ModifyMeetings(),
'/modifySingleMeeting': (BuildContext context) =>
ModifySingleMeeting(),
},
),
);
}
// End State
}

I literally faced the same issue, i neither could use a dialog nor a SnackBar, the problem is actually from not having the current context of your navigator route, here is my solution.

Change this:
SnackBarAction(
label: 'Go',
onPressed: () => null,
),
Into this:
SnackBarAction(
label: 'Go',
onPressed: () => print("pressed"),
),
According to the docs:
The label and onPressed arguments must be non-null.
https://api.flutter.dev/flutter/material/SnackBarAction/SnackBarAction.html

The problem is most likely due to the fact you're calling the scaffoldState key inside the StreamProvider.value widget but your routes are outside that widget. MaterialApp widget should be inside and incapsulate the Scaffold widget.

I have similar case in here the SnackBarAction show error because of const
**const** SnackBar(
content: Text('Added item to the Cart '),
duration: Duration(seconds: 2),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {},
));
},
SHOUD BE LIKE THIS
SnackBar(
content: Text('Added item to the Cart '),
duration: Duration(seconds: 2),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {},
));
},

Related

i am facing a problem in fetching image from firestore firebase using flutter

i am try to add userimage of user on bottom navigation bar
i have created the variable name inituserimage and its getter
but inituserimage is not storeing the complete url of the image fetched from firestore as a link so it could be load.
i am fetching the data in this file from firebase
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:straydogs/screens/LandingPage/landingUtils.dart';
import 'package:straydogs/services/Authentication.dart';
class FirebaseOperations with ChangeNotifier {
late UploadTask imageUploadTask;
late String initUserEmail, initUserName;
late String initUserImage;
String get getInitUserName => initUserName;
String get getInitUserEmail => initUserEmail;
String get getInitUserImage => initUserImage;
Future uploadUserAvatar(BuildContext context) async {
Reference imageReference = FirebaseStorage.instance.ref().child(
'userProfileAvatar/${Provider.of<LandingUtils>(context, listen: false).getUserAvatar.path}/${TimeOfDay.now()}');
imageUploadTask = imageReference.putFile(
Provider.of<LandingUtils>(context, listen: false).getUserAvatar);
await imageUploadTask.whenComplete(() {
print('Image Uploaded');
});
imageReference.getDownloadURL().then((url) {
Provider.of<LandingUtils>(context, listen: false).userAvatarUrl =
url.toString();
print(
'the user profile avatar url => ${Provider.of<LandingUtils>(context, listen: false).userAvatarUrl}');
notifyListeners();
});
}
Future createUserCollection(BuildContext context, dynamic data) async {
return FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.set(data);
}
Future initUserData(BuildContext context) {
return FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.get()
.then((doc) {
print('fetching user data');
initUserName = doc['username'];
initUserEmail = doc['useremail'];
initUserImage = doc['userimage'];
print(initUserName);
print(initUserEmail);
print(initUserImage);
notifyListeners();
});
}
}
here i am using the image to be displayed on bottom navigation bar
import 'package:custom_navigation_bar/custom_navigation_bar.dart';
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:straydogs/constants/Constantcolors.dart';
import 'package:straydogs/services/FirebaseOperations.dart';
class HomepageHelpers with ChangeNotifier {
ConstantColors constantColors = ConstantColors();
Widget bottomNavBar(BuildContext context, int index, PageController pageController) {
return CustomNavigationBar(
currentIndex: index,
bubbleCurve: Curves.bounceIn,
scaleCurve: Curves.decelerate,
selectedColor: constantColors.purple,
unSelectedColor: constantColors.whiteColor,
strokeColor: constantColors.purple,
scaleFactor: 0.5,
iconSize: 30.0,
onTap: (val) {
index = val;
pageController.jumpToPage(val);
notifyListeners();
},
backgroundColor: Color(0xff0e0021),
items: [
CustomNavigationBarItem(icon: Icon(EvaIcons.home)),
CustomNavigationBarItem(icon: Icon(EvaIcons.search)),
CustomNavigationBarItem(icon: Icon(Icons.messenger_rounded)),
CustomNavigationBarItem(
icon: CircleAvatar(
radius: 35.0,
backgroundColor: constantColors.blueGreyColor,
backgroundImage: NetworkImage(Provider.of<FirebaseOperations>(context,listen: false).getInitUserImage),
))
],
);
}
}
code error
screen error
in your FirebaseOperations you set the downloadURL to
Provider.of<LandingUtils>(context, listen: false).userAvatarUrl =
url.toString();
but in the Widget you use:
backgroundImage: NetworkImage(Provider.of<FirebaseOperations>(context,listen: false).getInitUserImage),
So the solution is to use the right provider because you never set initUserImage
That says also the error initUserImage has not been initialized.

google sign in button isn't working how to resolve

I have added google sign in button to my login page. but when I CLICK IT its not working at all. I REFER this video for the implementation. how to resolve this. I'm struggling to find the error. appreciate your help on this. all the firebase parts are done according to the video instructions. there's no error to displaying. just button not working.
//google_sign_in.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignInProvider extends ChangeNotifier{
final googleSignIn =GoogleSignIn();
GoogleSignInAccount? _user;
GoogleSignInAccount get user => _user!;
Future googleLogin()async{
final googleUser= await googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth =await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
notifyListeners(); //to update UI
}
}
//main.dart
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:lala_live/provider/google_sign_in.dart';
import 'package:lala_live/screens/login.dart';
import 'package:lala_live/screens/splashscreen.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
const bool USE_EMULATOR = false;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
if (USE_EMULATOR) {
_connectToFirebaseEmulator();
}
runApp(MyApp());
}
Future _connectToFirebaseEmulator() async {
final fireStorePort = "8080";
final authPort = 9099;
final localhost = Platform.isAndroid ? '10.0.2.2' : 'localhost';
FirebaseFirestore.instance.settings = Settings(
host: "$localhost:$fireStorePort",
sslEnabled: false,
persistenceEnabled: false,
);
await FirebaseAuth.instance.useAuthEmulator('http://$localhost:', authPort);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) => ChangeNotifierProvider(
create: (context)=> GoogleSignInProvider(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(fontFamily: 'Quicksand'),
home: FutureBuilder(
future: Future.delayed(Duration(seconds: 3)),
builder: (ctx, timer) => timer.connectionState == ConnectionState.done
? Login() //Screen to navigate to once the splashScreen is done.
: SplashScreen()),
),
);
}
//login.dart
Center(
child: SocialButton(
logo: 'asset/images/googleicon.png',
height: widgetheight,
width: width / 4,
text: 'Google',
onPressed: () {
final provider = Provider.of<GoogleSignInProvider>(context,listen:false);
provider.googleLogin();
},
color: containergrey)),
],
),
Try this,
maybe u forgot to async await
onPressed: () async {
final provider =
Provider.of<GoogleSignInProvider>(context, listen: false);
await provider.googleLogin();
},
googleSignIn.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignInProvider extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
GoogleSignInAccount get user => _user!;
Future googleLogin() async {
try {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {}
notifyListeners();
}
Future logout() async {
await googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
}
**SignInButton**
import 'package:flutter/material.dart';
class ButtonWidget extends StatelessWidget {
final String text;
final VoidCallback onClicked;
const ButtonWidget({
Key? key,
required this.text,
required this.onClicked,
}) : super(key: key);
#override
Widget build(BuildContext context) => ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
onPrimary: Colors.white,
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12),
),
child: Text(text),
onPressed: onClicked,
);
}
Widget buildUpgradeButton() => ButtonWidget(
text: Click to SignIn,
onClicked: () {
final provider =
Provider.of<GoogleSignInProvider>(context, listen: false);
provider.googleLogin();
});

Firebase Dart Tried to read a provider that threw during the creation of its value

I'm working on a authentication system right now, and I'm facing this error:
Bad state: Tried to read a provider that threw during the creation of its value.
The exception occurred during the creation of type AuthenticationService.
This is my main.dart:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:twofound/authentication.dart';
import 'package:twofound/database.dart';
import 'package:twofound/swipe.dart';
import 'package:twofound/map.dart';
import 'package:twofound/offers.dart';
import 'package:twofound/friends.dart';
import 'package:twofound/profile.dart';
import 'package:twofound/splash.dart';
import 'package:twofound/login.dart';
import 'package:twofound/register.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MainSeite());
await Firebase.initializeApp();
connectToFireBase();
}
class MainSeite extends StatefulWidget {
const MainSeite({Key? key}) : super(key: key);
#override
_MainSeiteState createState() => _MainSeiteState();
}
class _MainSeiteState extends State<MainSeite> {
int currentIndex = 0;
List<Widget> pages = [
const RegisterForm(),
const Swipe(),
const Map(),
const Chat(),
const Contacts(),
const Profile(),
];
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthenticationService>(
create: (_) => AuthenticationService(FirebaseAuth.instance),
),
StreamProvider(
create: (context) =>
context.read<AuthenticationService>().authStateChanges,
initialData: null,
),
],
child: MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.black,
selectedItemColor: Colors.orange,
unselectedItemColor: Colors.black,
currentIndex: currentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.people), label: "Swipe"),
BottomNavigationBarItem(icon: Icon(Icons.map), label: "Map"),
BottomNavigationBarItem(
icon: Icon(Icons.zoom_in_outlined),
label: "Activity Offers"),
BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Social")
],
onTap: (index) {
setState(() {
currentIndex = index;
});
},
),
body: SafeArea(child: pages[currentIndex]),
),
));
}
}
class AuthenticationWrapper extends StatelessWidget {
const AuthenticationWrapper({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User?>();
if (firebaseUser == null) {
return const RegisterForm();
}
return const MainSeite();
}
}
void connectToFireBase() async {
final FirebaseAuth authenticate = FirebaseAuth.instance;
UserCredential result = await authenticate.signInAnonymously();
User user = result.user!;
DatabaseService database = DatabaseService(user.uid);
database.setEntry("Test", "test text");
}
I want the user to see the register Page when logged out of Firebase and the Main Page when logged in. I used providers for this which are probably causing the error.
I'm very happy if you could help me because I'm new to dart and flutter.
It's impossible to say what caused the exception without the source for AuthenticationService. Please add it to your question. Also for future questions consider narrowing down the problem to the smallest bit of code that seems to be causing the problem(s). However, provide at least Minimal, Reproducible Example.
Edit:
Source for AuthenticationService looks ok. The exception is coming from StreamProvider.create. Here is ctx.read called before authService is available in current BuildContext. Scoping providers like this eliminates this problem.
#override
Widget build(BuildContext context) {
return Provider(
create: (_) => AuthenticationService(FirebaseAuth.instance),
child: StreamProvider(
create: (ctx) => ctx.read<AuthenticationService>().authStateChanges,
initialData: null,
child: MaterialApp(),
),
);
}

I am not able to catch the data from firebase messaging when my app is closed in Flutter

I am trying to catch key-value data from firebase messaging, i.e. by receiving notifications from firebase. I made a class for functionality and then assigned values to two global variables. Still, when I receive notification and click on it, no data is shown in my ui. Even title and body of notification is not shown when I start my app from scratch, i.e. first I run my app, close it, receive notification and then open it by clicking on it. I want that whether my app is closed, running in background or opened, key-value data could be feteched and desplayed on UI.
Here is my code -
variables.dart -
import 'package:flutter/cupertino.dart';
ValueNotifier<String> data = ValueNotifier("");
ValueNotifier<String> bodyData = ValueNotifier("");
notification.dart -
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_notifications/variables.dart';
Future<void> onBackgroundMessage(RemoteMessage message) async {
await Firebase.initializeApp();
if (message.data.containsKey("data")) {
data.value = message.data["data"];
}
if (message.data.containsKey("body")) {
bodyData.value = message.data['body'];
}
}
class Messaging {
final firebaseMessaging = FirebaseMessaging.instance;
final streamController = StreamController<String>.broadcast();
final titleController = StreamController<String>.broadcast();
final bodyController = StreamController<String>.broadcast();
setNotifications() {
FirebaseMessaging.onBackgroundMessage(onBackgroundMessage);
FirebaseMessaging.onMessage.listen((message) async {
if (message.data.containsKey('data')) {
streamController.sink.add(message.data['data']);
}
if (message.data.containsKey('notification')) {
streamController.sink.add(message.data['notification']);
}
titleController.sink
.add(message.notification?.title ?? "Recieved Null Title");
bodyController.sink
.add(message.notification?.body ?? "Recieved Null Body");
});
final token = firebaseMessaging
.getToken()
.then((value) => print("Token is - $value"));
}
dispose() {
streamController.close();
bodyController.close();
titleController.close();
}
}
main.dart -
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_notifications/notification.dart';
import 'package:flutter_application_notifications/variables.dart';
void main() async {
await init();
runApp(const MyApp());
}
Future init() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String notificationTitle = "No title";
String notificationBody = "No Body";
String notificationData = "No Data";
int _counter = 0;
#override
void initState() {
super.initState();
final firebaseMessaging = Messaging();
firebaseMessaging.setNotifications();
firebaseMessaging.streamController.stream.listen(_changeData);
firebaseMessaging.bodyController.stream.listen(_changeBody);
firebaseMessaging.titleController.stream.listen(_changeTitle);
}
_changeData(String message) {
setState(() {
notificationData = message;
});
}
_changeTitle(String message) {
setState(() {
notificationTitle = message;
});
}
_changeBody(String message) {
setState(() {
notificationBody = message;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Title is - $notificationTitle",
),
Text(
"Body is - $notificationBody",
),
Text(
"Data is - $notificationData",
),
ValueListenableBuilder(
valueListenable: data,
builder: (context, value, child) {
return Text('Received data is $value');
},
),
],
),
),
);
}
}

problem in flutter with fireStore in QuerySnapshot its always null

i wil put all the code below this explanation
so i just create a CollectionReference like this
in class DataBaseServices
final CollectionReference brewCollection =
Firestore.instance.collection('brews');
and i add data normally
after i use it in stream
Stream<QuerySnapshot> get brews {
return brewCollection.snapshots();
}
and i put the value in widget
Widget build(BuildContext context) {
return StreamProvider<QuerySnapshot>.value(
value: DataBaseServices().brews,
and in another widget
i call it
final snapshot = Provider.of<QuerySnapshot>(context);
and after i check here if it is null i find that it is null
the code :
class database
import 'package:cloud_firestore/cloud_firestore.dart';
class DataBaseServices {
final CollectionReference brewCollection =
Firestore.instance.collection('brews');
final String uid;
DataBaseServices({this.uid});
Future updateUserData({int sugar, String name, int strength}) async {
return await brewCollection.document(uid).setData(
{'sugar': sugar, 'name': name, 'strength': strength},
);
}
Stream<QuerySnapshot> get brews {
return brewCollection.snapshots();
}
}
home class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crewbrewapp/screens/home/brews_list.dart';
import 'package:crewbrewapp/services/auth.dart';
import 'package:crewbrewapp/services/database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
AuthServices _auth = AuthServices();
#override
Widget build(BuildContext context) {
return StreamProvider<QuerySnapshot>.value(
value: DataBaseServices().brews,
child: Scaffold(
backgroundColor: Colors.brown.shade100,
appBar: AppBar(
title: Text('Home'),
centerTitle: true,
backgroundColor: Colors.brown.shade500,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('Log out'),
onPressed: () async {
await _auth.signOut();
},
),
],
leading: Icon(Icons.menu),
),
body: BrewsList(),
),
);
}
}
class brewList
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crewbrewapp/screens/home/brew_tile.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:crewbrewapp/models/brew.dart';
class BrewsList extends StatefulWidget {
#override
_BrewsListState createState() => _BrewsListState();
}
class _BrewsListState extends State<BrewsList> {
List<Brew> brews;
#override
Widget build(BuildContext context) {
final snapshot = Provider.of<QuerySnapshot>(context);
if (snapshot != null) {
snapshot.documents.map(
(element) {
brews = [
Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
),
];
},
);
}
return brews == null
? Container(
child: Text('Empty'),
)
: ListView.builder(
itemCount: brews.length,
itemBuilder: (context, index) {
return BrewTile(brew: brews[index]);
},
);
}
}
i tried everything but it still show nothing
Rather you should assign brews to the whole map:
if (snapshot != null) {
brews = snapshot.documents.map(
(element) {
return Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
);
},
).toList();
}
I believe your snapshot is not quite created by the time it is called in brewList.
A progress indicator may work for you;
if (snapshot == null) return CircularProgressIndicator();
snapshot.documents.map(
(element) {
brews = [
Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
),
];
);
}
add if
call doc.data() - data with () operator ,see below code in the class BrewList:
final brews = Provider.of<QuerySnapshot>(context);
//print(brews);
if (brews != null) {
for (var doc in brews.docs) {
print(doc.data());
}
}
call BrewList() class with provider from Home class,
see below code in the class Home :
> return StreamProvider<QuerySnapshot>.value(
> initialData: null,
> value: DatabaseBrews(uid:'').brews,
> child: Scaffold(...
> body: BrewList(),)

Resources