My data from firestore not retrieve using dart flutter - firebase

I am using cloud fire store in flutter I did:
connected the app with the firebase
put the google-services.json in app buil.gradle
add the dependency and plugin
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
MyApp();
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'کوردی پۆلی یەک',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget{
List<Widget> makeListWidget(AsyncSnapshot snapshot){
return snapshot.data.documents.map<Widget>((document){
return ListTile(
title: Text(document["name"]),
);
}).toList();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("کوردی پۆلی یەک",style: TextStyle(color: Colors.white),),
backgroundColor: Colors.deepOrange,
),
body: Container(
child: StreamBuilder(
stream: Firestore.instance.collection('lesson').snapshots(),
builder: (context,snapshot){
switch(snapshot.connectionState){
case ConnectionState.none:
return Center(child: Text('No data'));
case ConnectionState.waiting:
return Center(
child:CircularProgressIndicator());
default:
return ListView(
children:makeListWidget(snapshot),
);
}
},
),
),
);
}
}
It is just loading and when ever I delete the connectionState.waiting gives me error:
NoSuchMethodError: The getter 'documents' was called on null. Receiver: null
Tried calling

Change the firestore security rules to the following:
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}

change the allow read, write: if true; to allow read, write;

Related

Flutter/Firestore/Provider - Error shown for split second then stream displayed, how can I load stream values on startup?

I am using a Stream Provider to access Firestore data and pass it around my app. The problem I am facing starts when I first run the app. Everything starts as normal but as I navigate to the screen where I am using the Stream values in a list view, I initially get an error before the UI rebuilds and the list items appear after a split second. This is the error I get:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building OurInboxPage(dirty, dependencies: [_InheritedProviderScope<List<InboxItem>>]):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
I'm guessing this has something to do with the load time to access the values and add them to the screen? How can I load all stream values when the app starts up to avoid this?
Here is my Stream code:
Stream<List<InboxItem>> get inboxitems {
return orderCollection
.where("sendTo", isEqualTo: FirebaseAuth.instance.currentUser.email)
.snapshots()
.map(
(QuerySnapshot querySnapshot) => querySnapshot.docs
.map(
(document) => InboxItem.fromFirestore(document),
)
.toList(),
);
}
I then add this to my list of Providers:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
StreamProvider<List<InboxItem>>.value(value: OurDatabase().inboxitems),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Consumer<OurUser>(
builder: (_, user, __) {
return MaterialApp(
title: 'My App',
theme: OurTheme().buildTheme(),
home: HomepageNavigator(),
);
},
);
}
}
And finally the page I want to display the stream items:
class OurInboxPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
List<InboxItem> inboxList = Provider.of<List<InboxItem>>(context);
return Scaffold(
body: Center(
child: ListView.builder(
itemCount: inboxList.length,
itemBuilder: (context, index) {
final InboxItem document = inboxList[index];
return Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(document.event),
Icon(Icons.arrow_forward_ios)
],
),
);
},
),
),
);
}
}
Thanks
Yeah its trying to build before the data is populated, hence the null error.
Wrap your ListView.builder in a StreamBuilder and having it show a loading indicator if there's no data.
StreamBuilder<List<InboxItem>>(
stream: // your stream here
builder: (context, snapshot) {
if (snapshot.hasData) {
return // your ListView here
} else {
return CircularProgressIndicator();
}
},
);
I'm assuming your not using the latest version of provider because the latest version requires StreamProvider to set initialData.
If you really want to use StreamProvider and don't want a null value, just set its initialData property.
FROM:
StreamProvider<List<InboxItem>>.value(value: OurDatabase().inboxitems),
TO:
StreamProvider<List<InboxItem>>.value(
value: OurDatabase().inboxitems,
initialData: <InboxItem>[], // <<<<< THIS ONE
),
If you want to display some progress indicator while getter function inboxitems is executed initially. You don't need to modify the StreamProvider, and just add a null checking in your OurInboxPage widget.
class OurInboxPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
final List<InboxItem>? inboxList =
Provider.of<List<InboxItem>?>(context, listen: false);
return Scaffold(
body: inboxList == null
? const CircularProgressIndicator()
: ListView.builder(
itemCount: inboxList.length,
itemBuilder: (_, __) => Container(
height: 100,
color: Colors.red,
),
),
);
}
}
There are 2 ways to solve the issue.
Use the progress bar while the data is loading.
StreamBuilder<int>(
stream: getStream(),
builder: (_, snapshot) {
if (snapshot.hasError) {
return Text('${snapshot.error}');
} else if (snapshot.hasData) {
return Text('${snapshot.data}');
}
return Center(child: CircularProgressIndicator()); // <-- Use Progress bar
},
)
Provide dummy data initially.
StreamBuilder<int>(
initialData: 0, // <-- Give dummy data
stream: getStream(),
builder: (_, snapshot) {
if (snapshot.hasError) return Text('${snapshot.error}');
return Text('${snapshot.data}');
},
)
Here, getStream() return Stream<int>.

Flutter Streambuilder not working as expected with Firebase

Not sure I am thinking about this right. According to my knowledge the Streambuilder is supposed to log you out if the user has been deleted from the backend which is Firebase.
The steps of what I am doing as of now -
loading the app
Signing in to the app
Loading firebase and deleting the signed in user from the backend.
I believe doing this would log me out from the app as well. Is that right?
Here is my code -
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp(
theme: ThemeData(
accentColor: Colors.orange,
primarySwatch: Colors.blue,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
print(FirebaseAuth.instance.authStateChanges());
if (snapshot.connectionState == ConnectionState.active) {
var user = snapshot.data;
if (user == null) {
return Welcome();
}
return Conversations("Logged in");
}
)
));
}
Firebase Authentication uses a combination of long-lived and short-lived tokens to manage login sessions, and it may take up to an hour before the short-lived token needs to be refresh and the client detects that the client is signed out.
If you waited for less time than an hour, that is probably the reason your authStateChanges() didn't fire with a new value: the token is still valid, so the client's auth state hasn't changed yet.
If you want to learn how to revoke the user's tokens, I recommend reading the documentation on that. Fair warning though: it is quite a bit more involved than simply signing in and out on the client.
If your goal is to be able to lock out users instantly, there are probably other ways to do that. For example, when using Firebase's Realtime Database or Firestore, it is quite common to keep a list of "blocked UIDs" in the database, and check against that in the security rules of your database.
When logging out by using signOut(), the state got updated right away, but it might not be the case when you delete the user.
The change might take a while to be notified to the stream at the front end. You can read more on that here: Firebase user deleted but still logged in on device
Firebase Authentication tokens are valid for one hour and cached on the user's device. It is automatically refreshed by the client SDK. Deleting the account doesn't proactively reach out to all the user's devices to delete the token.
You can try on this mini sign-in app with the provided signOut() method:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyApp(),
);
}
}
class LandingPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<User>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
User user = snapshot.data;
if (user == null) {
return Welcome();
}
return Conversations();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
},
);
}
}
class Welcome extends StatelessWidget {
Future<void> _signInAnonymously() async {
try {
await FirebaseAuth.instance.signInAnonymously();
} catch (e) {
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Sign in')),
body: Center(
child: RaisedButton(
child: Text('Sign in anonymously'),
onPressed: _signInAnonymously,
),
),
);
}
}
class Conversations extends StatelessWidget {
Future<void> _signOut() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e); // TODO: show dialog with error
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
actions: <Widget>[
FlatButton(
child: Text(
'Logout',
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
onPressed: _signOut,
),
],
),
);
}
}

How to have multiple app-wise streams in flutter, when one stream depends on the other?

I have two streams whose data I need to use app-wise.
My main obstacle is that one of the streams needs the other's data, thus, I cannot call a MultiProvider.
My current implementation looks as follows, however I do not like it: I think it is not ok to return multiple MaterialApps. Actually, my app turns black for a while, when changing from one MaterialApp to the other.
This is my current implementation:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamProvider<User>.value( //First, listen to the User Stream here
value: AuthService().user,
child: MyMaterialApp(),
);
}
}
class MyMaterialApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context); //To get the user data here, and use it bellow
if (user == null){ //If I don't have the User yet, return Loading()
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "myApp",
theme: myTheme(),
home: Loading(),
);
} else {
return StreamProvider<UserData>.value(
value: DatabaseService(uid: user.uid).userData, //Once I have it, use it to build the UserData Stream
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: "myApp",
theme: myTheme(),
home: Wrapper(),
initialRoute: '/',
routes: {
'/home': (context) => Wrapper(),
//...
}
),
);
}
}
}
Thank you very much!
Based on this post https://github.com/rrousselGit/provider/issues/222 I was able to solve it by doing the following:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
StreamProvider<User>.value(value: AuthService().user),
Consumer<User>(
builder: (context, user, child) => StreamProvider<UserData>.value(
value: DatabaseService(uid: user == null ? null : user.uid).userData,
child: child,
),
)
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: "myApp",
theme: myTheme(),
home: Wrapper(),
initialRoute: '/',
routes: {
'/home': (context) => Wrapper(),
//...
}
),
);
}
}
The Consumer listens to the User data and passes it to the next Stream.

Flutter Firebase RealTime Databasee not ordering properly with OrderByChild() [duplicate]

This question already has an answer here:
Flutter: Firebase Real-Time database orderByChild has no impact on query result
(1 answer)
Closed 2 years ago.
I'm creating a simple application with Firebase Realtime database where a user inputs a text and it gets added to a list of chats.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _firebaseRef = FirebaseDatabase().reference().child('chats');
TextEditingController _txtCtrl = TextEditingController();
#override
Widget build(BuildContext context) {
var comments = _firebaseRef.orderByChild('time').limitToLast(10);
return Scaffold(
body: Container(
child: SafeArea(
child: Column(
children: <Widget>[
Container(
child: Row(children: <Widget>[
Expanded(child: TextField(controller: _txtCtrl)),
SizedBox(
width: 80,
child: OutlineButton(
child: Text("Add"),
onPressed: () {
sendMessage();
}))
])),
StreamBuilder(
stream: comments.onValue,
builder: (context, snap) {
if (snap.hasData &&
!snap.hasError &&
snap.data.snapshot.value != null) {
Map data = snap.data.snapshot.value;
List item = [];
data.forEach(
(index, data) => item.add({"key": index, ...data}));
return Expanded(
child: ListView.builder(
itemCount: item.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(item[index]['message']),
);
},
),
);
} else
return Center(child: Text("No data"));
},
),
],
),
),
),
);
}
sendMessage() {
_firebaseRef.push().set({
"message": _txtCtrl.text,
'time': DateTime.now().millisecondsSinceEpoch
});
}
}
It stores and retrieves data perfectly. But when I try adding data, the new items are placed at random points in the list.
For example, in the image below, the last item I placed into the list was 'Nine'. But it was put in the center of the list:
I've tried sorting the list by timestamps, but it did nothing.
What could be causing this issue? And how can I fix it?
When you call snap.data.snapshot.value; the data in the snapshot (which is ordered) is converted to a Map<String, Object> which isn't ordered. To maintain the order, you'll want to listen to onChild... instead.
Note that FlutterFire has a convenient firebase_list library that handles most of the heavy lifting of onChild... for you.
Also see:
Flutter Firebase Database wrong timestamp order
Flutter sort Firebase snapshot by timestamp
Flutter: Firebase Real-Time database orderByChild has no impact on query result
This might work:
use a Query
Query comments = _firebaseRef.orderByChild('time').limitToLast(10);

Flutter: Items in StreamBuilder(Using firebase realtime database) are sorted randomly [duplicate]

This question already has an answer here:
Flutter: Firebase Real-Time database orderByChild has no impact on query result
(1 answer)
Closed 2 years ago.
I'm creating a simple application with Firebase Realtime database where a user inputs a text and it gets added to a list of chats.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _firebaseRef = FirebaseDatabase().reference().child('chats');
TextEditingController _txtCtrl = TextEditingController();
#override
Widget build(BuildContext context) {
var comments = _firebaseRef.orderByChild('time').limitToLast(10);
return Scaffold(
body: Container(
child: SafeArea(
child: Column(
children: <Widget>[
Container(
child: Row(children: <Widget>[
Expanded(child: TextField(controller: _txtCtrl)),
SizedBox(
width: 80,
child: OutlineButton(
child: Text("Add"),
onPressed: () {
sendMessage();
}))
])),
StreamBuilder(
stream: comments.onValue,
builder: (context, snap) {
if (snap.hasData &&
!snap.hasError &&
snap.data.snapshot.value != null) {
Map data = snap.data.snapshot.value;
List item = [];
data.forEach(
(index, data) => item.add({"key": index, ...data}));
return Expanded(
child: ListView.builder(
itemCount: item.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(item[index]['message']),
);
},
),
);
} else
return Center(child: Text("No data"));
},
),
],
),
),
),
);
}
sendMessage() {
_firebaseRef.push().set({
"message": _txtCtrl.text,
'time': DateTime.now().millisecondsSinceEpoch
});
}
}
It stores and retrieves data perfectly. But when I try adding data, the new items are placed at random points in the list.
For example, in the image below, the last item I placed into the list was 'Nine'. But it was put in the center of the list:
I've tried sorting the list by timestamps, but it did nothing.
What could be causing this issue? And how can I fix it?
When you call snap.data.snapshot.value; the data in the snapshot (which is ordered) is converted to a Map<String, Object> which isn't ordered. To maintain the order, you'll want to listen to onChild... instead.
Note that FlutterFire has a convenient firebase_list library that handles most of the heavy lifting of onChild... for you.
Also see:
Flutter Firebase Database wrong timestamp order
Flutter sort Firebase snapshot by timestamp
Flutter: Firebase Real-Time database orderByChild has no impact on query result
This might work:
use a Query
Query comments = _firebaseRef.orderByChild('time').limitToLast(10);

Resources