flutter waning schedule binding while using listview builder - firebase

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Bookings extends StatefulWidget {
const Bookings({Key? key}) : super(key: key);
#override
State<Bookings> createState() => _BookingsState();
}
class _BookingsState extends State<Bookings> {
final String auth = FirebaseAuth.instance.currentUser!.uid;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red[200],
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("Bookings").where('UserID',isEqualTo: "$auth").snapshots(),
builder: (context,snapshot){
if(snapshot.hasError){
return Text("Something Went Wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(
color: Colors.redAccent,
),
);
}
if(snapshot.hasData){
final data = snapshot.requireData;
var len = snapshot.data!.size;
return ListView.builder(
itemCount: data.size,
itemBuilder: (BuildContext context, int index){
return Card(
elevation: 4,
child: ListTile(
leading: Container(
child: Image.network(image(data,index)),
),
title: Text("${data.docs[index]["Place"]}",
style: TextStyle(
fontSize: 20,
),
),
),
);
});
}
else{
return Text("sdf");
}
},
)
);
}
String image(data,index){
final img = FirebaseFirestore.instance.collection("Places").where('Name',isEqualTo: "${data.docs[index]["Place"]}").snapshots();
print(img);
return img.toString();
}
}
The error is
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/snackbar/snackbar.dart:452:22: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance!.addPostFrameCallback(
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/router_report.dart:53:22: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart').
WidgetsBinding.instance!.addPostFrameCallback((_) {
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/simple/get_controllers.dart:90:20: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart').
WidgetsBinding.instance!.addObserver(this);
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/simple/get_controllers.dart:96:20: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/widgets/binding.dart').
WidgetsBinding.instance!.removeObserver(this);
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/rx_flutter/rx_notifier.dart:130:22: Warning: Operand of null-aware operation '?.' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance?.addPostFrameCallback((_) => onReady());
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_state_manager/src/rx_flutter/rx_disposable.dart:20:22: Warning: Operand of null-aware operation '?.' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance?.addPostFrameCallback((_) => onReady());
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/extension_navigation.dart:357:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance!.addPostFrameCallback((_) {
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/extension_navigation.dart:468:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('/C:/src/flutter/packages/flutter/lib/src/scheduler/binding.dart').
SchedulerBinding.instance!.addPostFrameCallback((_) {
^
Restarted application in 2,457ms.
W/DynamiteModule(30694): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
E/Parcel (30694): Reading a NULL string not supported here.
I/DynamiteModule(30694): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller(30694): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
I/System.out(30694): [socket]:check permission begin!
E/flutter (30694): [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: Null check operator used on a null value, stack trace: #0 StatefulElement.state (package:flutter/src/widgets/framework.dart:4925:44)
E/flutter (30694): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:2542:47)
E/flutter (30694): #2 Navigator.pushReplacement (package:flutter/src/widgets/navigator.dart:2103:22)
E/flutter (30694): #3 _LoadingState.build. (package:tourism_app/screens/loading.dart:17:17)
E/flutter (30694): #4 new Future.delayed. (dart:async/future.dart:423:39)
E/flutter (30694): #5 Timer._createTimer. (dart:async-patch/timer_patch.dart:18:15)
E/flutter (30694): #6 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (30694): #7 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (30694): #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (30694):

It's something to do with the latest Flutter 3.0 update.
Try running dart fix --apply to fix the app code but it won't fix issues in the packages you are using.
See if you can find the latest version for the packages you are using to check if the problem is solved.
Check this for more details.

Related

Class 'DocumentSnapshot' has no instance getter 'doc'. Receiver: Instance of 'DocumentSnapshot' Tried calling: doc

I recently got started with firebase firestore and this is one error I cant seem to find a answer to, I tried writing snapshot.data.documents as docs, doc and document after looking at answers for similar questions but it is still throwing the same error. what do I do?
firestore version I am using is cloud_firestore: ^1.0.7
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// import 'package:vola1/colors.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
class test extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
// floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('countries')
.doc('nW9L4LGpn2MZVyiTyUII')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Loading data.. please wait..');
return Column(
children: <Widget>[
Text(
snapshot.data.doc[0]['name'],
style: TextStyle(fontSize: 20),
),
],
);
},
));
}
}
the exception it is throwing
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#af0fe):
Class 'DocumentSnapshot' has no instance getter 'documents'.
Receiver: Instance of 'DocumentSnapshot'
Tried calling: documents
The relevant error-causing widget was:
StreamBuilder<DocumentSnapshot> file:///D:/flutter%20course/vola1/lib/test.dart:14:15
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 test.build.<anonymous closure> (package:vola1/test.dart:24:29)
#2 StreamBuilder.build (package:flutter/src/widgets/async.dart:545:81)
#3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:124:48)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
...
====================================================================================================
To get the data from a DocumentSnapshot, use the data getter which retrieves all fields in the document as a Map;
docs is for the QuerySnapshot class.
Change this code below:
snapshot.data.doc[0]['name'],
to this:
snapshot.data['name'],

Shared Preference in flutter Isolate

I'm new to flutter and I just learned how to use isolates in Dart. When I try to access shared preference via an isolate it throws the given below error. This error also appears when I try to access Firebase analytics and remote config. How can I resolve this issue and access SharedPreference, FirebaseRemote config, FirebaseFirestore inside an isolate?
[ERROR:flutter/runtime/dart_isolate.cc(882)] Unhandled exception:
E/flutter (23694): ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter (23694): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter (23694): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
E/flutter (23694): #0 defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:92:7)
E/flutter (23694): #1 defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:105:4)
E/flutter (23694): #2 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:143:62)
E/flutter (23694): #3 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:149:36)
E/flutter (23694): #4 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12)
E/flutter (23694): #5 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:359:49)
E/flutter (23694): #6 MethodChannelSharedPreferencesStore.getAll (package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:54:22)
E/flutter (23694): #7 SharedPreferences._getSharedPreferencesMap (package:shared_preferences/shared_preferences.dart:191:57)
E/flutter (23694): #8 SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:58:19)
E/flutter (23694): #9 _wraperState.islt (package:spynett/main.dart:122:55)
E/flutter (23694): <asynchronous suspension>
E/flutter (23694): #10 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:304:17)
E/flutter (23694): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await setupLocator();
runApp(MyApp());
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
startinitsetup();
});
}
Future startinitsetup() async{
debugPrint('Calling setup');
await _dynamiclink.handledynamiclink();
await _pushNotificationService.initilalise();
await _remoteConfigService.initialise();
ReceivePort reciveport = ReceivePort();
Isolate.spawn(islt, reciveport.sendPort);
SendPort childSendPort = await reciveport.first;
ReceivePort responceport = ReceivePort();
childSendPort.send(['message',responceport.sendPort]);
await responceport.first;
}
static Future<int> islt(SendPort mainSendPort) async{
ReceivePort childRecivePort = ReceivePort();
mainSendPort.send(childRecivePort.sendPort);
await for (var message in childRecivePort){
SendPort replyport = message[1];
SharedPreferences _pref = await SharedPreferences.getInstance();
replyport.send('done');
}
}
You can copy paste run full code below
To use SharedPreferences in Isolate, you can use package https://pub.dev/packages/flutter_isolate
You can change from
Isolate.spawn(islt, reciveport.sendPort);
to
FlutterIsolate.spawn(islt, reciveport.sendPort);
output of full test code
I/flutter (12689): Calling setup
...
I/flutter (12689): test test
I/flutter (12689): isolate when msg recived
I/flutter (12689): reply done
full test code
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
//await Firebase.initializeApp();
//await setupLocator();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
startinitsetup();
});
}
Future startinitsetup() async {
debugPrint('Calling setup');
ReceivePort reciveport = ReceivePort();
FlutterIsolate.spawn(islt, reciveport.sendPort);
SendPort childSendPort = await reciveport.first;
ReceivePort responceport = ReceivePort();
childSendPort.send(['message', responceport.sendPort]);
String reply = await responceport.first;
print("reply $reply");
}
static Future<int> islt(SendPort mainSendPort) async {
ReceivePort childRecivePort = ReceivePort();
mainSendPort.send(childRecivePort.sendPort);
await for (var message in childRecivePort) {
SendPort replyport = message[1];
SharedPreferences _pref = await SharedPreferences.getInstance();
await _pref.setString("yourKey", "test");
String testPref = _pref.get("yourKey");
print("test $testPref");
debugPrint('isolate when msg recived');
replyport.send('done');
}
}
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter - A non-null String must be provided to a Text widget

I am having an error as regards fetching data from firestore using futureBuilder. When I do a print of snapshot.data without calling a Text widget, I get an instance of 'User'.
Without Calling author.fullname
body: ListView.builder(
itemCount: _posts.length,
itemBuilder: (BuildContext context, int index) {
Post post = _posts[index];
return FutureBuilder(
future: DatabaseService.getUserWithId(post.authorid),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data);
User author = snapshot.data;
return Column(
children: <Widget>[],
);
}
}
return SizedBox.shrink();
Output
Performing hot restart...
Restarted application in 1,146ms.
flutter: Instance of 'User'
flutter: Instance of 'User'
However when I try to call for the fullname of the user from firestore, it returns null
body: ListView.builder(
itemCount: _posts.length,
itemBuilder: (BuildContext context, int index) {
Post post = _posts[index];
return FutureBuilder(
future: DatabaseService.getUserWithId(post.authorid),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data);
User author = snapshot.data;
return Column(
children: <Widget>[
Text(author.fullname)
],
);
}
}
return SizedBox.shrink();
Output
Performing hot restart...
Restarted application in 1,042ms.
flutter: Instance of 'User'
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
flutter: The following assertion was thrown building FutureBuilder<User>(dirty, state:
flutter: _FutureBuilderState<User>#23d74):
flutter: A non-null String must be provided to a Text widget.
flutter: 'package:flutter/src/widgets/text.dart':
flutter: Failed assertion: line 285 pos 10: 'data != null'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: The relevant error-causing widget was:
flutter: FutureBuilder<User> file:///Users/momo/Desktop/combine/lib/screens/home.dart:65:18
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2 new Text (package:flutter/src/widgets/text.dart:285:10)
flutter: #3_HomeState.build.<anonymous closure>.<anonymous closure> (package:combine/screens/home.dart:75:23)
flutter: #4 _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
flutter: #5 StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
flutter: #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
flutter: #7 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
flutter: #8 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2432:33)
flutter: #9 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:773:20)
flutter: #10 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:283:5)
flutter: #11 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1102:15)
flutter: #12 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1041:9)
flutter: #13 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:957:5)
flutter: #17 _invoke (dart:ui/hooks.dart:259:10)
flutter: #18 _drawFrame (dart:ui/hooks.dart:217:3)
flutter: (elided 5 frames from class _AssertionError and package dart:async)
User Class
class User {
final String id;
final String email;
final String password;
final String fullname;
User(
{this.id,
this.email,
this.password,
this.fullname,});
factory User.fromDoc(DocumentSnapshot doc) {
return User(
id: doc.documentID,
email: doc['email'],
fullname: doc['fullname'],
);
}
}
You must provide an empty text in case the name is null
return Column(
children: <Widget>[
Text(author.fullname == null? '' : author.fullname)
],
);

Flutter NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot>

I am getting this error while trying to fetch user data from the cloud_firestore but it's only getting me this error when for the first time, users login to the app and navigate to the profile screen. if I hot restart or rerun the app, while in login state error goes away.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══
flutter: The following NoSuchMethodError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state:
flutter: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#f33a1):
flutter: The method '[]' was called on null.
flutter: Receiver: null
flutter: Tried calling: []("name")
flutter:
flutter: User-created ancestor of the error-causing widget was:
flutter: SliverFillRemaining
flutter: file:///Users/ishangavidusha/Development/MUD/mud_mobile_app/lib/screens/profile_screen.dart:102:13
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
flutter: #1 new User.from (package:mud_mobile_app/models/user_model.dart:23:22)
flutter: #2 _ProfileScreenState.build.<anonymous closure> (package:mud_mobile_app/screens/profile_screen.dart:107:38)
flutter: #3 StreamBuilder.build (package:flutter/src/widgets/async.dart:425:74)
flutter: #4 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
flutter: #5 StatefulElement.build (package:flutter/src/widgets/framework.dart:4047:27)
flutter: #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3941:15)
flutter: #7 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
flutter: #8 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2348:33)
flutter: #9 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:760:20)
flutter: #10 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:280:5)
flutter: #11 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1033:15)
flutter: #12 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:975:9)
flutter: #13 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:891:5)
flutter: #17 _invoke (dart:ui/hooks.dart:249:10)
flutter: #18 _drawFrame (dart:ui/hooks.dart:207:3)
flutter: (elided 3 frames from package dart:async)
Emulator Screenshot
And this is the user model I use >
class User {
final String id;
final String name;
final String profileImageUrl;
final String email;
User({this.id, this.name, this.profileImageUrl, this.email});
factory User.fromDoc(DocumentSnapshot doc) {
return User(
id: doc.documentID,
name: doc['name'],
profileImageUrl: doc['profileImageUrl'],
email: doc['email'],
);
}
}
FutureBuilder >
SliverFillRemaining(
child: FutureBuilder(
future: _getUserData(widget.userId),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(50.0),
child: Center(
child: CircularProgressIndicator(),
),
);
}
User user = User.fromDoc(snapshot.data);
return Column(
children: <Widget>[
Padding(...),
Container(...),
Container(...),
],
);
}
)
)
And the Funtion DocumentSnapshot return >
Future<DocumentSnapshot> _getUserData(userId) async {
return Firestore.instance.collection('users').document(userId).get();
}
"StreamBuilder dirty state" warnings are usually shown if the snapshot data doesn't have a safety check. This ensures that the snapshot contains data. However, it seems if (!snapshot.hasData) is set as a safety check on the snippet you've provided.
From the details you've given, the error seems to only occur during first user login, but the error goes away on hot restart or app restart. I suggest checking if the method _getUserData(String userId) is able to receive the userId upon the first user login where the error usually occurs. Null seems to be passed on where the error occurs based from the logs you've provided.
flutter: The method '[]' was called on null.
flutter: Receiver: null
flutter: Tried calling: []("name")
FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text("Full Name: ${data['full_name']} ${data['last_name']}");
}
return Text("loading");
If you are using above similar type code and then get same error , check the firebase documentId in collection name and snapshot

'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