Flutter Firestore StreamBuilder getting null value initially - firebase

I'm trying to get data from firestore by using stream builder method. initially, when I run the app I don't get any data from firebase. I'm getting
Invalid value: Valid value range is empty: 0.
once I reload app the data is available
please find the code bellow
Widget build(BuildContext context) {
return StreamBuilder(
stream: Firestore.instance
.collection('users/')
.where('uid', isEqualTo: _userUID)
.snapshots(),
builder: (BuildContext context, userSnapshot) {
if (!userSnapshot.hasData) return WidgetFunctions().loadingWidget();
return StreamBuilder(
stream: Firestore.instance
.collection('products')
.where('latest', isEqualTo: true)
.snapshots(),
builder: (cuserSnapshotontext, snapshot) {
if (!snapshot.hasData) return WidgetFunctions().loadingWidget();
if (snapshot.data.documents.length == 0)
return const Center(
child: Text(
"Not Available",
style: TextStyle(fontSize: 30.0, color: Colors.grey),
),
);
if (!userSnapshot.data.documents[0]['productViewPermission']) {
print('place6');
return const Center(
child: Text(
'You dont have permission to view products \n please contect us',
style: TextStyle(
fontSize: 18.0,
color: Colors.red,
fontWeight: FontWeight.bold),
));
}
return GridView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: snapshot.data.documents.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemBuilder: (BuildContext context, int index) {
return SingleProduct(
productCatagory: snapshot.data.documents[index]
['productCatogary'],
productName: snapshot.data.documents[index]
['productName'],
imageURL: snapshot.data.documents[index]['imageURLS']
[0],
price: userSnapshot.data.documents[0]
['priceViewpermission']
? snapshot.data.documents[index]['price'].toDouble()
: "To view price please contect us",
discountBool: snapshot.data.documents[index]
['discount'],
discountValue: snapshot.data.documents[index]
['discountValue'],
index: index,
description: snapshot.data.documents[index]
['description'],
make: snapshot.data.documents[index]['make'],
karat: snapshot.data.documents[index]['karat'],
waight:
snapshot.data.documents[index]['waight'].toDouble(),
condition: snapshot.data.documents[index]['condition'],
populer: snapshot.data.documents[index]['populer'],
isAvailable: snapshot.data.documents[index]
['isAvailable']);
},
);
});
});
}
I/flutter ( 3686): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3686): The following RangeError was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter ( 3686): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#02fde):
I/flutter ( 3686): RangeError (index): Invalid value: Valid value range is empty: 0
I/flutter ( 3686): When the exception was thrown, this was the stack:
I/flutter ( 3686): #0 List.[] (dart:core-patch/growable_array.dart:145:60)
I/flutter ( 3686): #1 _PopularProductsContainerState.build.<anonymous closure>.<anonymous closure> (package:thaya_factory/Components/HomePageComponents/CategoryComponent/LatestProductsComponent.dart:54:49)
I/flutter ( 3686): #2 StreamBuilder.build (package:flutter/src/widgets/async.dart:425:74)
I/flutter ( 3686): #3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 3686): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4012:27)
I/flutter ( 3686): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3924:15)
I/flutter ( 3686): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
I/flutter ( 3686): #7 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2340:33)
I/flutter ( 3686): #8 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 3686): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)
I/flutter ( 3686): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter ( 3686): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:958:9)
I/flutter ( 3686): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:874:5)
I/flutter ( 3686): #16 _invoke (dart:ui/hooks.dart:236:10)
I/flutter ( 3686): #17 _drawFrame (dart:ui/hooks.dart:194:3)
I/flutter ( 3686): (elided 3 frames from package dart:async)
I/flutter ( 3686): ═══════════════════════
Please help me to fix the issue
Thanks in advance

Well first of all, this block of code has invalid syntax:
if (snapshot.data.documents.length == 0)
return const Center(
child: Text(
"Not Available",
style: TextStyle(fontSize: 30.0, color: Colors.grey),
),
);
You forgot the opening and closing brackets on the if statement.
And secondly, try an else if on the second if statement, because now, when snapshot.data.documents.length returns null, it will still check for !userSnapshot.data.documents[0], though the list is empty, which is the cause for your RangeError.
So try this:
if (snapshot.data.documents.length == 0) {
return const Center(
child: Text(
"Not Available",
style: TextStyle(fontSize: 30.0, color: Colors.grey),
),
);
} else if (!userSnapshot.data.documents[0]['productViewPermission']) {
print('place6');
return const Center(
child: Text(
'You dont have permission to view products \n please contect us',
style: TextStyle(
fontSize: 18.0,
color: Colors.red,
fontWeight: FontWeight.bold),
)
);
}

This is because itemCount of GridView is accessing no data snaphsot.
Try doing
itemCount = snapshot.data== null ? 0 : snapshot.data.documents.length;

Related

Exception caught by widgets library Bad state: field does not exist within the DocumentSnapshotPlatform

I am reading the data from firebase firestore I have different collections when I am reading from this one this error comes out.
Here is my code
final _firestore = FirebaseFirestore.instance;
var DTSpH, datePH, pPHH;
class PH extends StatefulWidget {
static const String id = 'pH';
#override
_LightState createState() => _LightState();
}
class _LightState extends State<PH> {
_LightState();
Widget build(BuildContext context) {
while (true) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
Navigator.pop(context);
}),
],
title: Text('Previous Light Data'),
backgroundColor: Colors.orange,
),
floatingActionButton: null,
body: StreamBuilder(
stream: _firestore.collection('Previous pH Data').snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
datePH = (document["DataAndTime"]);
pPHH = (document["pH"]);
print(pPHH);
DTSpH= pPHH.toString();
return Center(
child: Container(
width: MediaQuery.of(context).size.width / 1.1,
height: MediaQuery.of(context).size.height / 20,
child: Text("pH: " + DTSpH + " " + "On " +datePH ),
),
);
}).toList(),
);
},
),
);
}
}
}
This is the error
======== Exception caught by widgets library =======================================================
The following StateError was thrown building StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(dirty, dependencies: [MediaQuery], state: _StreamBuilderBaseState<QuerySnapshot<Map<String, dynamic>>, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>>#5bb4e):
Bad state: field does not exist within the DocumentSnapshotPlatform
The relevant error-causing widget was:
StreamBuilder<QuerySnapshot<Map<String, dynamic>>> StreamBuilder:file:///Users/mahmoudabdelaziz/StudioProjects/newgreen/lib/screens/pH.dart:40:15
When the exception was thrown, this was the stack:
#0 DocumentSnapshotPlatform.get._findKeyValueInMap (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:87:7)
#1 DocumentSnapshotPlatform.get._findComponent (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:105:23)
#2 DocumentSnapshotPlatform.get (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:121:12)
#3 _JsonDocumentSnapshot.get (package:cloud_firestore/src/document_snapshot.dart:92:48)
#4 _JsonDocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:96:40)
#5 _LightState.build.<anonymous closure>.<anonymous closure> (package:QUGreen/screens/pH.dart:52:33)
#6 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#7 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#8 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27)
#9 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
#10 new List.of (dart:core-patch/array_patch.dart:51:28)
#11 ListIterable.toList (dart:_internal/iterable.dart:213:44)
#12 _LightState.build.<anonymous closure> (package:QUGreen/screens/pH.dart:62:18)
#13 StreamBuilder.build (package:flutter/src/widgets/async.dart:442:81)
#14 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:124:48)
#15 StatefulElement.build (package:flutter/src/widgets/framework.dart:4918:27)
#16 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4805:15)
#17 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4976:11)
#18 Element.rebuild (package:flutter/src/widgets/framework.dart:4528:5)
#19 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2672:19)
#20 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#21 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:367:5)
#22 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1145:15)
#23 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
#24 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:996:5)
#28 _invoke (dart:ui/hooks.dart:151:10)
#29 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#30 _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
====================================================================================================
But the reading process is done successfully because I printed it I do not know what to do any help please
Try changing this line in your code from this:
body: StreamBuilder(
stream: _firestore.collection('Previous pH Data').snapshots(),
to this:
body: StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('Previous pH Data').snapshots(),

Bad state: field does not exist within the DocumentSnapshotPlatform. Flutter and firebase

I'm trying to build a list from a collection from firebase database but I'm running into a problem with the stream builder snapshots.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("users").snapshots().where((event) => true),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data != null) {
return ListView.builder(
itemBuilder: (listContext, index) =>
buildItem(snapshot.data.docs[index]),
itemCount: snapshot.data.docs.length,
);
}
return Container();
},
));
}
buildItem(doc) {
return (userId != doc['id'])
? GestureDetector(
onTap: () {
//Navigator.push(context, MaterialPageRoute(builder: (context) => Page(docs: doc)));
},
child: Card(
color: Colors.black,
child: Container(
height: 60,
child: Center(
child: Text(doc['name'],
style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
),
),
)
: Container();
}
Here is the whole error:
======== Exception caught by widgets library =======================================================
The following StateError was thrown building:
Bad state: field does not exist within the DocumentSnapshotPlatform
When the exception was thrown, this was the stack:
#0 DocumentSnapshotPlatform.get._findKeyValueInMap (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:86:7)
#1 DocumentSnapshotPlatform.get._findComponent (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:104:41)
#2 DocumentSnapshotPlatform.get (package:cloud_firestore_platform_interface/src/platform_interface/platform_interface_document_snapshot.dart:120:26)
#3 _JsonDocumentSnapshot.get (package:cloud_firestore/src/document_snapshot.dart:92:48)
#4 _JsonDocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:96:40)
...
====================================================================================================
The builder is building the list but its giving a red error section directly below it.
The doc in your buildItem method is a DocumentSnapshot object, which doesn't have an [] defined as far as I know.
I think you're missing a call to data():
userId != doc.data()['id']
If you get another error message after this change, please search for it on Stack Overflow first as I know there have been some recent changes in how types are exposed from a document snapshot.

Flutter code returning "The getter 'text' was called on null."

The below code doesn't seem to have any error, i built it using google Firebase but cant login.
This is the login page code
import 'package:flutter/material.dart';
import 'utils/firebase_auth.dart';
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
TextEditingController _emailController;
TextEditingController _passwordController;
#override
void initstate() {
_emailController = TextEditingController(text: "");
_passwordController = TextEditingController(text: "");
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Image(
image: AssetImage("Assets/login.jpg"),
fit: BoxFit.cover,
color: Colors.grey,
colorBlendMode: BlendMode.lighten,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 110,
width: 110,
child: Image(
image: AssetImage("Assets/house.png"),
fit: BoxFit.fill,
colorBlendMode: BlendMode.lighten,
),
),
Form(
child: Theme(
data: ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.deepPurple,
inputDecorationTheme: InputDecorationTheme(
hintStyle: TextStyle(
color: Colors.black,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
),
child: Container(
padding: const EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
TextFormField(
controller: _emailController,
style: TextStyle(
color: Colors.black,
fontSize: 18.5,
fontWeight: FontWeight.w400,
fontStyle: FontStyle.italic,
),
decoration: InputDecoration(
hintText: "Enter Email",
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
),
TextFormField(
controller: _passwordController,
style: TextStyle(
color: Colors.black,
fontSize: 18.5,
fontWeight: FontWeight.w400,
fontStyle: FontStyle.italic,
),
decoration: InputDecoration(
hintText: "Enter Password",
prefixIcon: Icon(Icons.remove_red_eye),
),
keyboardType: TextInputType.text,
obscureText: true,
),
const SizedBox(height: 15.0),
MaterialButton(
minWidth: 1000.0,
color: Colors.deepPurple,
child: Text(
"LOGIN",
style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 20,
color: Colors.white),
),
onPressed: () async{
if (_emailController.text.isEmpty ||
_passwordController.text.isEmpty)
{
print("Please Enter Email and Password");
return;
}
bool res = await AuthProvider().signInWithEmail(
_emailController.text,
_passwordController.text);
if(res){
print("Login failed");
}
},
),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(top: 30.0),
child: Text(
"Sign Up?",
style: TextStyle(
color: Colors.deepPurple,
fontStyle: FontStyle.italic,
fontSize: 15.0,
),
),
),
Container(
padding: EdgeInsets.only(top: 30.0, left: 125.0),
child: Text(
"forgot password?",
style: TextStyle(
color: Colors.deepPurple,
fontStyle: FontStyle.italic,
fontSize: 15.0,
),
),
),
],
),
],
),
),
),
),
],
),
],
),
);
}
}
This is the main.dart code containing the future
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'home.dart';
import 'loginpage.dart';
import 'splash.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.deepPurple,
accentColor: Colors.purpleAccent,
),
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context, AsyncSnapshot<FirebaseUser> snapshot){
if(snapshot.connectionState == ConnectionState.waiting)
return SplashPage();
if(!snapshot.hasData || snapshot.data == null)
return LoginPage();
return HomePage();
},
);
}
}
This is the error message
E/flutter ( 1365): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The getter 'text' was called on null.
E/flutter ( 1365): Receiver: null
E/flutter ( 1365): Tried calling: text
E/flutter ( 1365): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter ( 1365): #1 _LoginPageState.build.<anonymous closure>
package:househunt/loginpage.dart:105
E/flutter ( 1365): #2 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:706
E/flutter ( 1365): #3 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:789
E/flutter ( 1365): #4 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182
E/flutter ( 1365): #5 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:486
E/flutter ( 1365): #6 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:264
E/flutter ( 1365): #7 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:199
E/flutter ( 1365): #8 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:467
E/flutter ( 1365): #9 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:76
E/flutter ( 1365): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:117
E/flutter ( 1365): #11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter ( 1365): #12 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:115
E/flutter ( 1365): #13 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:101
E/flutter ( 1365): #14 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:218
E/flutter ( 1365): #15 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:198
E/flutter ( 1365): #16 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:156
E/flutter ( 1365): #17 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:102
E/flutter ( 1365): #18 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:86
E/flutter ( 1365): #19 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter ( 1365): #20 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 1365): #21 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 1365): #22 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter ( 1365): #23 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter ( 1365):
I have searched the internet but could not find a fix, has anyone else had this trouble?
You have a typo in the method initstate. It should be initState... your initialization code is not running.

Flutter Firestore and StreamBuilder

I'm trying to build a google newsfeed like structure for my flutter app. There is no error in the design part. I tried with some dummy data and the widget build correctly. When I'm trying to convert firestore data into widget, the widget won't build and nothing in the screen. Below is StreamBuilder code
Widget build(BuildContext context) {
height = MediaQuery.of(context).size.height;
width = MediaQuery.of(context).size.width;
return Container(
color: Colors.green[50],
height: height,
width: width,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: height * 0.04,
),
Container(
height: height * 0.12,
width: width * 0.90,
color: Colors.green[50],
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(left: width * 0.10),
child: Text('UPCOMING EVENTS',
style: GoogleFonts.tenaliRamakrishna(
textStyle: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w500))),
),
)
],
),
),
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('Events').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'),);
}
return ListView(
children: snapshot.data.documents
.map<Widget>((DocumentSnapshot document) {
return eventCard(
imageUrl: document['ImageUrl'],
title: document['Title'],
description: document['Description'],
venue: document['Venue'],
date: document['Date'],
time: document['Time']);
}).toList(),
);
},
)
],
),
));
}
my widget code is
Widget eventCard(
{String imageUrl,
String title,
String description,
String venue,
String date,
String time}) {
return Padding(
padding: EdgeInsets.all(10),
child: InkWell(
onTap: null,
child: Container(
height: height * 0.50,
width: width * 0.90,
decoration:
kEventsPage.copyWith(borderRadius: BorderRadius.circular(20)),
child: Column(
children: <Widget>[
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20)),
child: Image.network(
imageUrl,
width: width * 90,
fit: BoxFit.fill,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent loadingProgress) {
if (loadingProgress == null) return child;
return Align(
alignment: Alignment.bottomRight,
child: LinearProgressIndicator(
backgroundColor: Colors.grey,
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes
: null,
),
);
},
),
),
flex: 6,
),
Expanded(
flex: 4,
child: Padding(
padding: EdgeInsets.only(left: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Flexible(
child: Text(
title,
style: GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 20, fontWeight: FontWeight.w500)),
),
),
Flexible(
child: Text(
description,
style: GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 15, fontWeight: FontWeight.w400)),
),
),
Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: <Widget>[
Text(
'Venue: ',
style: GoogleFonts.roboto(
fontWeight: FontWeight.w900),
),
Text(venue)
],
),
Row(
children: <Widget>[
Text(
'Date: ',
style: GoogleFonts.roboto(
fontWeight: FontWeight.w900),
),
Text(date)
],
),
Row(
children: <Widget>[
Text(
'Time: ',
style: GoogleFonts.roboto(
fontWeight: FontWeight.w900),
),
Text(time)
],
)
],
))
],
),
),
)
],
),
),
),
);
}
And the error is
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9553): The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter ( 9553): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#21f5c):
I/flutter ( 9553): The getter 'documents' was called on null.
I/flutter ( 9553): Receiver: null
I/flutter ( 9553): Tried calling: documents
I/flutter ( 9553):
I/flutter ( 9553): The relevant error-causing widget was:
I/flutter ( 9553): StreamBuilder<QuerySnapshot>
I/flutter ( 9553): file:///D:/Praveen/Flutter/FlutterApps/employee_tracking/lib/screens/Events.dart:169:15
I/flutter ( 9553):
I/flutter ( 9553): When the exception was thrown, this was the stack:
I/flutter ( 9553): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter ( 9553): #1 _EventsState.build.<anonymous closure> (package:employeetracking/screens/Events.dart:176:45)
I/flutter ( 9553): #2 StreamBuilder.build (package:flutter/src/widgets/async.dart:509:81)
I/flutter ( 9553): #3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:127:48)
I/flutter ( 9553): #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter ( 9553): #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter ( 9553): #6 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter ( 9553): #7 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter ( 9553): #8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
I/flutter ( 9553): #9 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
I/flutter ( 9553): #10 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
I/flutter ( 9553): #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter ( 9553): #12 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5947:32)
I/flutter ( 9553): ... Normal element mounting (111 frames)
I/flutter ( 9553): #123 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter ( 9553): #124 Element.updateChild (package:flutter/src/widgets/framework.dart:3211:20)
I/flutter ( 9553): #125 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
I/flutter ( 9553): #126 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter ( 9553): #127 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter ( 9553): #128 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
I/flutter ( 9553): #129 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
I/flutter ( 9553): #130 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter ( 9553): #131 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter ( 9553): #132 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter ( 9553): #133 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter ( 9553): #137 _invoke (dart:ui/hooks.dart:261:10)
I/flutter ( 9553): #138 _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter ( 9553): (elided 3 frames from dart:async)
I/flutter ( 9553):
I/flutter ( 9553): ════════════════════════════════════════════════════════════════════════════════════════════════════
W/libEGL ( 9553): EGLNativeWindowType 0x78761c2010 disconnect failed
I/SurfaceView( 9553): delay destroy surface control
E/SurfaceView( 9553): surfacePositionLost_uiRtSync mSurfaceControl = null
W/libEGL ( 9553): EGLNativeWindowType 0x78760c5010 disconnect failed
I/flutter ( 9553): Another exception was thrown: Vertical viewport was given unbounded height.
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderViewport#48731 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderViewport#48731 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderIgnorePointer#fd3bc relayoutBoundary=up10 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderSemanticsAnnotations#0133e relayoutBoundary=up9 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderPointerListener#5ee9f relayoutBoundary=up8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderSemanticsGestureHandler#4cd88 relayoutBoundary=up7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderPointerListener#35642 relayoutBoundary=up6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: _RenderScrollSemantics#54fe5 relayoutBoundary=up5 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#15475 relayoutBoundary=up4 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderCustomPaint#66748 relayoutBoundary=up3 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#01ac9 relayoutBoundary=up2 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#01ac9 relayoutBoundary=up2 NEEDS-PAINT
I/flutter ( 9553): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#01ac9 relayoutBoundary=up2 NEEDS-PAINT
W/FlutterJNI( 9553): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: lyokone/locationstream. Response ID: 0
W/FlutterJNI( 9553): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: lyokone/locationstream. Response ID: 0
I found the reason. It's because using ListView inside the Column widget. Column expands to the maximum size in main axis direction (vertical axis), and so does the ListView
Solution:
Use either Flexible or Expanded if you want to allow ListView to take up entire left space in Column.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
There are a couple of things to try.
1) Replace
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'),);
}
with:
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'),);
}
if (!snapshot.hasData) {
return Center(child: Text('No data'),);
}
This will give the builder the time to fetch the data.
2) If you see No data, then go to Firebase console > Database > firestore and check if there is a collection called Events at the root of the database. Check the capitalization, check if there are not extra invisible space.
If this exists, click and Check if there are data in there

'firebase/main.dart': Failed assertion

I have made a simple baby names project using firebase on flutter,
after successfully going throught the tutorial, the app gives this error : " package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes] ! = null': is not true. "
Help for the same.
MY CODE -:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
final dummySnapshot = [
{"name": "Filip", "votes": 15},
{"name": "Abraham", "votes": 14},
{"name": "Richard", "votes": 11},
{"name": "Ike", "votes": 10},
{"name": "Justin", "votes": 1},
];
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Baby Names',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() {
return _MyHomePageState();
}
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Baby Name Votes')),
body: _buildBody(context),
);
}
Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('baby').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return _buildList(context, snapshot.data.documents);
},
);
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => print(record),
),
),
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
Output :
Performing hot restart...
Syncing files to device Redmi Note 4...
Restarted application in 1,994ms.
I/flutter ( 2257): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2257): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2257): _StreamBuilderBaseState>#94c3a):
I/flutter ( 2257): 'package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes'] != null': is not
I/flutter ( 2257): true.
I/flutter ( 2257):
I/flutter ( 2257): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2257): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2257): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2257): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2257):
I/flutter ( 2257): When the exception was thrown, this was the stack:
I/flutter ( 2257): #2 new Record.fromMap (package:firebase_demo/main.dart:86:16)
I/flutter ( 2257): #3 new Record.fromSnapshot (package:firebase_demo/main.dart:91:14)
I/flutter ( 2257): #4 _MyHomePageState._buildListItem (package:firebase_demo/main.dart:59:27)
I/flutter ( 2257): #5 _MyHomePageState._buildList. (package:firebase_demo/main.dart:54:40)
I/flutter ( 2257): #6 MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
I/flutter ( 2257): #7 ListIterable.toList (dart:_internal/iterable.dart:219:19)
I/flutter ( 2257): #8 _MyHomePageState._buildList (package:firebase_demo/main.dart:54:71)
I/flutter ( 2257): #9 _MyHomePageState._buildBody. (package:firebase_demo/main.dart:46:16)
I/flutter ( 2257): #10 StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 2257): #11 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2257): #12 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 2257): #13 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 2257): #14 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 2257): #15 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 2257): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 2257): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 2257): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 2257): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 2257): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 2257): #21 _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 2257): #22 _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 2257): (elided 2 frames from class _AssertionError)
I/flutter ( 2257): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/1.gpu ( 2257): type=1400 audit(0.0:191179): avc: denied { ioctl } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 ioctlcmd=945 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/1.gpu ( 2257): type=1400 audit(0.0:191180): avc: denied { read write } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/an.firebasedem( 2257): Waiting for a blocking GC ProfileSaver
I/an.firebasedem( 2257): WaitForGcToComplete blocked ProfileSaver on ProfileSaver for 30.771ms
Maybe you can check your collection name in the firebase first.
stream: Firestore.instance.collection('your_collection_name_here').snapshots(),
Make sure your fields in the Firebase match with the proprieties of Record.
e.g:
name matches name field from the database
votes matches votes field from the database

Resources