Another exception was thrown: FormatException: Invalid number (at character 1) - flutter

Why does the error Another exception was thrown: FormatException: Invalid number (at character 1) occur on my screen for a few microseconds before all is back to normal. Sometimes it doesn't even occur. Below is my StreamBuilder function:
_delivered() {
print('In the delivered function:${resId},${customerId}, ');
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('restaurants')
.document(resId)
.collection('customers')
.document(customer)
.collection('orders')
.where('deliveryTime', isGreaterThan: '')
.snapshots(),
builder: (context, snapshot) {
print('Does snapshop have data? ${snapshot.hasData}');
if (!snapshot.hasData) return Container();
List deliveredListFromServer = snapshot.data.documents;
return Expanded(
child: ListView(
shrinkWrap: true,
children: deliveredListFromServer.map((item) {
print('document id: ${item.documentID}');
return InkWell(
child: SizedBox(
height: 50,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 80,
child: Text(
item['orderBy']['username'],
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
SizedBox(
width: 5,
),
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
children: item['order'].map<Widget>((item) {
return SizedBox(
width: 80,
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'${item['qty']} ${item['drinkName']}',
overflow: TextOverflow.ellipsis,
),
),
);
}).toList(),
), //
),
SizedBox(
width: 5,
),
SizedBox(
width: 60,
child: Text(DateFormat('h:mm a').format(
DateTime.fromMillisecondsSinceEpoch(
int.parse(item['deliveryTime'])))),
)
],
),
),
onTap: () {
_deliveredDetail(item);
},
);
}).toList(),
),
);
});
}
This is my console:
I/flutter (11506): In the delivered function:XufIsxA8a24lLhO6gTr1,zMrQmcoQwci9bVVRo6tx,
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562
I/flutter (11506): document id: 1579595374166
I/flutter (11506): Another exception was thrown: FormatException: Invalid number (at character 1)
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562
From the console, I don't even understand why it's bringing document id: 1579595374166 from the database. Only document id: 1579534059562 has a deliveryTime set. The database has 6 records, only one has a deliveryTime set. Others are empty "" strings.
So after a few milliseconds, everything works as expected i.e. the proper UI with only one item for the database showing on the screen. It looks like everything is back to normal the second time the stream returns only one document. In fact, the only time it doesn't bring the red screen is when the console looks like this:
I/flutter (11506): In the delivered function:XufIsxA8a24lLhO6gTr1,zMrQmcoQwci9bVVRo6tx,
I/flutter (11506): Does snapshop have data? false
I/flutter (11506): Does snapshop have data? true
I/flutter (11506): document id: 1579534059562
This also means the streamBuilder is passing incorrect data to the list (and probable source of error). Why is the query returning the wrong results sometimes?!

This error occurs when you are fetching a data which is null, I encountered the same issue and was able to solve it by removing that null data from my firestore database.
I would suggest you check the data in the collection from where you are fetching the list, one of the fields must be null there.

My answer may not be applicable to this instance, but I have also got the same error "Invalid number (at character 1)", the place where I get the error points me to where I have used the variable name of my TextEditingController
The problem with my case was that I have already used a TextEditingController with the same name (also not as a private variable) in another point of my application and have not disposed it after using.
After I disposed all of my TextEditingControllers my problem got solved !

if an error occurs in the parameter, you can add an isEmpty condition for your parameter value.
ex :
// define currency
final _controller = TextEditingController(); static const _locale = 'id'; static const _symbol = 'Rp. '; String _formatNumber(String s) =>
NumberFormat.decimalPattern(
_locale,
).format(s.isEmpty ? 0 : int.parse(s)); String get _currency =>
NumberFormat.compactSimpleCurrency( locale: _locale, name: _symbol).currencySymbol;
//textfield
TextfieldWidget( prefixText: Text(_currency, style: Theme.of(context).textTheme.subtitle1),
controller: _controller,
onChanged: (string) {
string =
'${_formatNumber(string.replaceAll(',', ''))}';
_controller.value = TextEditingValue(
text: string,
selection: TextSelection.collapsed(
offset: string.length ?? null),
);
}, ),

Ensure that you check that the value is not equal to "" or null
if (value != "")

Related

How can I solve "NoSuchMethodError: The method "[]" was called on null

gamelist is a String List of document names in the collection. The questionMap value is an array named "text" field obtained from the firestore document using the gamelist value as key. I would like to update the questionMap when I press the pass button, When I press the pass button, I see that the questionMap is indeed updated when I print in this code, but the screen is not redrawn and I get the error as shown in the title. It is a dirty code, but I would like to know how to solve it.
This is my code:
class PlayPage extends StatefulWidget {
List gameList;
Map questionMap;
String category;
int myScore;
PlayPage({
required this.gameList,
required this.category,
required this.myScore,
required this.questionMap,
});
#override
State<PlayPage> createState() => _PlayPageState();
}
class _PlayPageState extends State<PlayPage> {
int quizNumber = 0;
int listNumber = 0;
var db = FirebaseFirestore.instance;
void changeQuiz() {
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Stack(
children: [
Card(
child: SizedBox(
height: double.infinity,
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(
top: 20, bottom: 200, left: 20, right: 20),
child: Text(
widget.questionMap[widget.gameList[listNumber]][quizNumber],
style: const TextStyle(fontSize: 20),
),
),
),
),
),
Positioned(
right: 10,
bottom: 30,
child: Column(
children: [
ElevatedButton(
child: const Text(
"Pass",
style: TextStyle(fontSize: 30),
),
onPressed: () {
listNumber += 1;
quizNumber = 0;
setState(
() {
var docRef = db
.collection(widget.category)
.doc(widget.gameList[listNumber]);
docRef.get().then(
(DocumentSnapshot doc) {
var data = doc.data() as Map<String, dynamic>;
List questions = selectQuiz(
data["text"],
);
widget.questionMap = {
widget.gameList[listNumber]: questions
};
print(widget.questionMap);
},
);
},
);
},
),
const SizedBox(height: 30),
SizedBox(
width: 70,
height: 70,
child: FloatingActionButton(
backgroundColor:
(quizNumber < 9) ? Colors.teal : Colors.grey,
child: const Icon(
Icons.arrow_forward,
size: 35,
),
onPressed: () {
if (quizNumber < 9) {
setState(
() {
quizNumber += 1;
},
);
}
},
),
),
],
),
)
],
),
);
}
}
Make sure that the object you are trying to access is not null before you try to access it.
The error message NoSuchMethodError: The method '[]' was called on null is telling you that you've called the index ([]) operator on null.
This error occurs when a method or property has been called but it does not exist in the current context due to some type mismatch or incorrect data format being passed into it as an argument. Examine the stack trace and look at the line number where the failure occurred.
As mentioned here
For example, let's imagine you see:
Unhandled exception:
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("data")
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 main (file:///Users/cbracken/foo.dart:3:23)
...
The stack trace above is telling you that the call on the null object
was in main on line 3 of file foo.dart. Further, it's telling you
that the [] operator was called with the parameter 'data'. If I
look at that line in my code and it says var foo = json['localteam']['data'], then I would deduce that
json['localteam'] is returning null.
It can be solved by identifying the exact location where it occurred followed by fixing typos/mistakes related argument passing along with ensuring proper variable declarations.

Value detected of type null when passing data via routes in flutter

This error just been a while before the data passed successfully from loading screen.
The loading screen that passing data :
if i print the instance on here, the error is not appeared
void setupWorldTime() async {
WorldTime instance = WorldTime(location: 'Jawa Timur', flag: 'jakarta.png', url: 'Asia/Jakarta');
await instance.getTime();
Navigator.pushReplacementNamed(context, '/home', arguments: {
'location': instance.location,
'flag': instance.flag,
'time': instance.time,
});
}
The home screen which is receiving data :
Map data = {};
#override
Widget build(BuildContext context) {
data = ModalRoute.of(context)!.settings.arguments as Map;
print(data['location']);
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.only(top: 50),
child: Column(
children: [
TextButton.icon(
onPressed: () {
Navigator.pushNamed(context, '/location');
},
icon: const Icon(Icons.edit_location),
label: const Text('Edit Location'),
),
const SizedBox(
height: 20,
),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Text(
data['time'],
style: const TextStyle(
fontSize: 30,
),
),
]),
],
),
),
),
);
}
print(data['location']); printing the data perfectly, but before it the error above showing instantly, is that mean the print method expected the value of data is null before it is receive the value? how to fix it
Your method setupWorldTime is an async function and will not call the Navigator.pushReplacementNamed bit until instance.getTime() has returned. Because your home screen starts without its arguments set, data = ModalRoute.of(context)!.settings.arguments as Map will set data to null, leading to your error. Only once instance.getTime() has returned will build() be called again, this time with data != null and your message disappears.
To fix this, in your build function you should test for data == null and show something else (like a loading indicator) if data is indeed still null, or use a FutureBuilder (preferred).

How can i solve RangeError (index): Invalid value: Valid value range is empty: 0?

Each time a page was built, we used onCalendarCreated to import the totoList for the current date.
However, RangeError (index): Invalid value: Valid value range is empty: 0 error occurs.
I think it's a problem with ListViewBuilder, how can I solve this error?
Here is my full error code
RangeError (index): Invalid value: Valid value range is empty: 0
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:177:60)
#1 _TimeTableState.todoCard (package:take_a_note_project/calender_view/month_table.dart:155:27)
#2 _TimeTableState.build.<anonymous closure> (package:take_a_note_project/calender_view/month_table.dart:113:40)
#3 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:449:22)
#4 SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1130:28)
// get todoList code
onDaySelected: (date, events, holidays) {
setState(() {
todoListHandler.selectedEvents = events;
todoListHandler.getDone(controller.selectedDay);
});
},
onCalendarCreated: (DateTime first, DateTime last, CalendarFormat format) {
todoListHandler.doneTodo.isEmpty
? CircularProgressIndicator()
: todoListHandler.getDone(controller.selectedDay);
},
//Listbuilder code
Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: todoListHandler.doneTodo.length,
itemBuilder: (context, index) {
return GestureDetector(
child: todoCard(context,
todoListHandler.doneTodo,
index
),
);
}
),
)
//todoCard code
Widget todoCard(BuildContext context, todoItem, int index) {
Color color = Colors.white38;
Color titleColor = Colors.white;
String toDo = todoItem[index].todo;
String startTime = todoItem[index].startTime;
String endTime = todoItem[index].endTime;
return Card(
elevation: 5,
color: color,
child: ListTile(
leading: Icon(CupertinoIcons.check_mark_circled_solid, color: Colors.greenAccent, size: 45,),
title: Text(
(startTime != null) ? "$startTime ~ $endTime" : "- ~ -"
,style: TextStyle(
fontWeight: FontWeight.normal, fontSize: 20, color: titleColor)),
subtitle: Text(toDo, style: TextStyle(
fontWeight: FontWeight.normal, fontSize: 30, color: Colors.white70
),),
)
);
}
I am getting the same erorr.. may be this is because the Array is overflowing with too much data.

StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>):

I cant able to retrive the data from Firestore and getting Error as below,
════════ Exception caught by widgets library
═══════════════════════════════════════════════════════ The following
assertion was thrown building StreamBuilder(dirty,
state: _StreamBuilderBaseState<QuerySnapshot,
AsyncSnapshot>#e568b): A build function returned null.
The offending widget is: StreamBuilder Build functions
must never return null.
To return an empty space that causes the building widget to fill
available room, return "Container()". To return an empty space that
takes as little room as possible, return "Container(width: 0.0,
height: 0.0)".
The relevant error-causing widget was: StreamBuilder
file:...dart:140:15 When the exception was thrown, this was the stack:
#0 debugWidgetBuilderValue. (package:flutter/src/widgets/debug.dart:300:7)
#1 _Closure.call (dart:core-patch/function.dart)
#2 debugWidgetBuilderValue (package:flutter/src/widgets/debug.dart:321:4)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4569:7)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4737:11) ...
Below is my code.
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("currency").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData){
print('test pharse');
Text("Loading.....");}
else {
List<DropdownMenuItem> currencyItems = [];
for (int i = 0; i < snapshot.data.documents.length; i++) {
DocumentSnapshot snap = snapshot.data.documents[i];
currencyItems.add(
DropdownMenuItem(
child: Text(
snap.documentID,
style: TextStyle(color: Color(0xff11b719)),
),
value: "${snap.documentID}",
),
);
}
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.mail,
size: 25.0, color: Color(0xff11b719)),
SizedBox(width: 50.0),
DropdownButton(
items: currencyItems,
onChanged: (currencyValue) {
final snackBar = SnackBar(
content: Text(
'Selected Currency value is $currencyValue',
style: TextStyle(color: Color(0xff11b719)),
),
);
Scaffold.of(context).showSnackBar(snackBar);
setState(() {
selectedCurrency = currencyValue;
});
},
value: selectedCurrency,
isExpanded: false,
hint: new Text(
"Choose Currency Type",
style: TextStyle(color: Color(0xff11b719)),
),
),
],
);
}
}),
You need to add a return before the Text widget in the !snapshot.hasData section of the StreamBuilder
if (!snapshot.hasData){
print('test phrase');
return Text("Loading.....");
}

Error: Class 'QuerySnapshot' has no instance getter 'data'

I'm trying to creat a UI screen with 3 tabs in it. RecentItem, ReviewItem and Profile. however there's some backend problem in recentitem widget. With the error shown: Class 'QuerySnapshot' has no instance getter 'data'.
Ps: The whole code is quite big hence I have shared a doc for the whole code: https://docs.google.com/document/d/1qs4ajPJ0DBjserBJ3iBZmPXPz1zTP7tIYSh8vceVQn8/edit?usp=sharing
RecentItems():
Widget RecentItems() {
return Padding(
padding: const EdgeInsets.all(10.0),
child: StreamBuilder(
stream: Firestore.instance
.collection("users")
.document(uid)
.collection("recent")
.snapshots(),
builder: (context, snapshot) {
print(snapshot.data);
List orders = List.from(Map.from(snapshot.data.data)['orders']);
Map order;
for (int i = 0; i < orders.length; i++) {
if (orders[i]['orderId'] == widget.map['orderId'] &&
orders[i]['homemaker'] == widget.map['homemaker']) {
order = orders[i];
break;
}
}
if (snapshot.data.isEmpty) {
return Center(
child:
Text("OOPS, Looks like no one is serving!"));
}
print(order);
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasData) {
print(snapshot.data.documents[0].data);
return Container(
height: 400,
child: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.all(10.0),
width: MediaQuery
.of(context)
.size
.width,
height: 85,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Expanded(child: Text(
"${snapshot.data.documents[index]
.data["dishname"]}", style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold),)),
//Icon: how to access if food is veg or not
],
),
// SizedBox(height:5),
Row(
children: <Widget>[
Expanded(child: Text(
"${snapshot.data.documents[index]
.data["homemaker"]}",
style: TextStyle(fontSize: 10),)),
Text("${snapshot.data.documents[index]
.data["rating"]}",
style: TextStyle(fontSize: 15)),
Icon(
Icons.star, color: Colors.yellow.shade800,
size: 20,)
],
),
SizedBox(height: 5),
//How to access order date
Text(
"Ordered ${DateTime
.parse(order['order_placed_at']
.toDate()
.toString())
.day}/${DateTime
.parse(order['order_placed_at']
.toDate()
.toString())
.month}/${DateTime
.parse(order['order_placed_at']
.toDate()
.toString())
.year}}",
style: TextStyle(fontSize: 15.0,
fontWeight: FontWeight.bold),
),
],
),
),
);
}),
);
} //
}),
);
}
The Error Message is:
The getter 'data' was called on null.
Receiver: null
Tried calling: data
The relevant error-causing widget was:
StreamBuilder<QuerySnapshot> file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:434:14
════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (28940): Instance of 'QuerySnapshot'
════════ (3) Exception caught by widgets library ═══════════════════════════════════════════════════
Class 'QuerySnapshot' has no instance getter 'data'.
Receiver: Instance of 'QuerySnapshot'
Tried calling: data
The relevant error-causing widget was:
StreamBuilder<QuerySnapshot> file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:434:14
Several things or all might be causing this:
the print from the first line of builder. If snapshot was indeed empty you would already be calling data without first checking if it is empty.
snapshot.data.data which I think is a typo in the second line of builder
The fact that you are doing operations on snapshot without first checking for snapshot.hasData, snapshot.data.documents.length != 0 to ensure that you are not doing operations on null snapshots.
You should also be able to check specifically which line is causing the error by pressing on the error messages, one of the error messages should contain a link to the specific line (not shown in your question, should be somewhere between the long stacks of error messages)
This code:
Firestore.instance
.collection("users")
.document(uid)
.collection("recent")
.snapshots()
returns a Stream of type QuerySnapshot, the problem is here:
List orders = List.from(Map.from(snapshot.data.data)['orders']);
the code snapshot.data will return an instance of QuerySnapshot and QuerySnapshot does not contain a instance variable called data. So, if you want to a list of documents then you have to do the following:
List<DocumentSnapshot> orders = snapshot.data.documents;
https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query_snapshot.dart#L17