Error: The method '>=' was called on null - entity-framework

I get some error in this code plz find out.
I have some error in running this method but I can't understand what this error want to say. This error crashes my app:
import 'dart:math';
class Brain{
Brain({this.height,this.weight});
final int height;
final int weight;
double _bmi;
String calculatebmi(){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);
}
String getresult(){
if (_bmi >= 25){
return 'OVERWEIGHT';
}
else if (_bmi > 18.5 ){
return 'NORAML';
}
else{
return 'UNDERWEIGHT';
}
}
error=>
I/flutter (29335): The following NoSuchMethodError was thrown building Builder(dirty):
I/flutter (29335): The method '>=' was called on null.
I/flutter (29335): Receiver: null
I/flutter (29335): Tried calling: >=(25)
I/flutter (29335):
I/flutter (29335): The relevant error-causing widget was:

You are never setting _bmi to a value when you create the class, so unless you call your calculatebmi() function before calling getResult() it will throw that error since you can't do a comparison operation like >= on a null value in dart.
Try changing your initialization of _bmi to double _bmi = 0; or change your constructor to set it on creation with your calculation weight / pow( height/100, 2).

Related

The findAncestorStateOfType is returning null as a value

My code :
class NavPage extends StatefulWidget {
NavPage({#required this.name, #required this.id});
static void setLocale(BuildContext context, Locale locale) {
_NavPageState state = context.findAncestorStateOfType<_NavPageState>();
print(state);/* printed as null because findAncestorStateOfType returned null*/
state.setLocale(locale);
}
#override
_NavPageState createState() => _NavPageState();
}
Error:
I/flutter (10132): null
E/flutter (10132): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'setLocale' was called on null.
E/flutter (10132): Receiver: null
So here I was trying to internationalize my app but I faced this problem in the last stages of coding.
I think where you would want to call the state object would be after the build method actually
See this for more insight
https://api.flutter.dev/flutter/widgets/BuildContext/findAncestorStateOfType.html
Method not before it.

The following NoSuchMethodError was thrown building Builder(dirty): The method '>=' was called on null. Receiver: null The relevant error-causing was:

So, I want to pass data to a new screen, by calling methods and passing it into a String. The first method calc.calculateBMI() was passed in successfully into bmiResult.. But I got the error below for calc.getInterpretation
First Screen's Code.
ButtomButton(
buttonTitle: 'CALCULATE',
onTap: (){
CalculatorBrain calc = CalculatorBrain(height: height, weight: weight);
Navigator.push(context, MaterialPageRoute(builder: (context){
return ResultsPage(
bmiResult: calc.calculateBMI(),
interpretation: calc.getInterpretation(),
);
}));
},
),
import 'dart:math';
class CalculatorBrain {
CalculatorBrain({this.height, this.weight});
final int height;
final int weight;
double _bmi;
String calculateBMI() {
double _bmi = weight / pow(height/100, 2);
return _bmi.toStringAsFixed(1);
}
String getInterpretation() {
if (_bmi >= 25){
return 'You have a higher than normal body weight. try to exercise more';
} else if (_bmi > 18.5) {
return 'You have a normal body weight. Good job!';
} else {
return 'You have a lower than normal body weight. You can eat a bit more';
}
}
}
The Error I got
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Builder(dirty):
The method '>=' was called on null.
Receiver: null
Tried calling: >=(27)
The relevant error-causing widget was:
MaterialApp file:///C:/Users/MICHEAL/AndroidStudioProjects/bmi_calculator/lib/main.dart:9:12
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 CalculatorBrain.getInterpretation (package:bmi_calculator/calculator_brain.dart:27:14)
#2 _InputPageState.build.<anonymous closure>.<anonymous closure> (package:bmi_calculator/screens/input_page.dart:214:40)
#3 MaterialPageRoute.buildContent (package:flutter/src/material/page.dart:55:55)
#4 MaterialRouteTransitionMixin.buildPage (package:flutter/src/material/page.dart:108:27)
...
====================================================================================================
The error in the code above is caused by the fact that we're not initializing the _bmi variable inside the CalculatorBrain class.
To do so we can proceed by using the following code:
import 'dart:math';
class CalculatorBrain {
CalculatorBrain({this.height, this.weight}) {
_bmi = weight / pow(height/100, 2);
}
final int height;
final int weight;
double _bmi;
String calculateBMI() =>
_bmi.toStringAsFixed(1);
String getInterpretation() {
if (_bmi >= 25){
return 'You have a higher than normal body weight. try to exercise more';
} else if (_bmi > 18.5) {
return 'You have a normal body weight. Good job!';
} else {
return 'You have a lower than normal body weight. You can eat a bit more';
}
}
}
The same snippet with null-safety would be:
import 'dart:math';
class CalculatorBrain {
CalculatorBrain({required this.height, required this.weight}) {
_bmi = weight / pow(height / 100, 2);
}
final int height;
final int weight;
late double _bmi;
String calculateBMI() => _bmi.toStringAsFixed(1);
String getInterpretation() {
if (_bmi >= 25) {
return 'You have a higher than normal body weight. try to exercise more';
} else if (_bmi > 18.5) {
return 'You have a normal body weight. Good job!';
} else {
return 'You have a lower than normal body weight. You can eat a bit more';
}
}
}

Flutter: Provider shows Exception but app run fine while using default listen:true

I'm Using provider in initState() to call the api but if I use listen:false then it does not update UI and it always shows me loader but if I use listen:true then app works fine but in the terminal it shows me exception and tells me write listen:false.
My UI,
class ChopperNewsCard extends StatefulWidget {
#override
_ChopperNewsCardState createState() => _ChopperNewsCardState();
}
class _ChopperNewsCardState extends State<ChopperNewsCard> {
ScrollController scrollController = ScrollController();
int currentPage = 5;
ChopperApiStore _apiStore = ChopperApiStore();
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
_apiStore = Provider.of<ChopperApiStore>(context,);//<--- here it tells me to write listen:false
});
_apiStore.getResponse(currentPage);
scrollController.addListener(() {
if (scrollController.position.pixels ==
scrollController.position.maxScrollExtent) {
if (currentPage < 20) {
currentPage = currentPage + 5;
_apiStore.getResponse(currentPage);
}
}
});
}
#override
void dispose() {
scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Observer(builder: (context) {
return Container(
height: height * 0.37,
width: double.infinity,
child: _apiStore.res.articles == null
? CircularProgressIndicator()
: ListView.builder(...),
);
});
}
}
api calling class,
class ChopperApiStore extends _ChopperApiStore with _$ChopperApiStore{}
abstract class _ChopperApiStore with Store{
ApiCall apiCall = ApiCall();
#observable
ChopperNews res = ChopperNews();
#action
Future<void> getResponse(int page) async {
var data = await apiCall.getNews(page);
res = data;
}
}
the error I'm getting,
======== Exception caught by scheduler library =====================================================
The following assertion was thrown during a scheduler callback:
Tried to listen to a value exposed with provider, from outside of the widget tree.
This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.
To fix, write:
Provider.of<ChopperApiStore>(context, listen: false);
It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.
The context used was: ChopperNewsCard(dependencies: [MediaQuery], state: _ChopperNewsCardState#8f6cd)
'package:provider/src/provider.dart':
Failed assertion: line 262 pos 7: 'context.owner.debugBuilding ||
listen == false ||
debugIsInInheritedProviderUpdate'
When the exception was thrown, this was the stack:
#2 Provider.of (package:provider/src/provider.dart:262:7)
#3 _ChopperNewsCardState.initState.<anonymous closure> (package:fruitley/week-5/bonus/chopper/widgets/chopper_news_card.dart:32:28)
#4 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
#5 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1063:9)
#6 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5)
...
I think if you want to use listen:true to have the build method called you are suppose to override didChangeDependencies rather then initState Checkout this article it might help https://medium.com/swlh/flutter-provider-and-didchangedependencies-15678f502262
ok I'm dumb. I didn't even need to use addPostFrameCallback.
I just removed it and if I want to use provider outside of widget tree that I must use listen:false as it was showing in the exception so now everything makes sense.

NoSuchMethodError, Exception caught by widgets library

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Builder(dirty):
The method '>=' was called on null.
Receiver: null
Tried calling: >=(25)
The relevant error-causing widget was:
MaterialApp file:///C:/Users/Ahmed/AndroidStudioProjects/bmi_calc/lib/main.dart:8:12
When the exception was thrown, this was the stack:
0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
1 calculator.getresult (package:bmicalc/calculator.dart:14:14)
2 _InputPageState.build.. (package:bmicalc/input_page.dart:226:97)
3 MaterialPageRoute.buildPage (package:flutter/src/material/page.dart:87:27)
4 _ModalScopeState.build. (package:flutter/src/widgets/routes.dart:710:43)
At #1 my code is
class calculator {
calculator({this.height, this.weight});
final int height;
final int weight;
double _bmi;
String calculatebmi() {
_bmi = (weight / pow(height / 100, 2));
return _bmi.toStringAsFixed(1);
}
String getresult() {
if (_bmi >= 25) {
return 'Overweight';
} else if (_bmi > 18.5) {
return 'Normal';
} else {
return 'Underweight';
}
return ' ';
}
String getRemarks() {
if (_bmi >= 25) {
return 'Your weight is more than average body weight, try to excercise.';
} else if (_bmi > 18.5) {
return 'Your weight is normal';
} else {
return 'Your weight is less than average body weight, try to eat more';
}
}
}
At #2
`GestureDetector(
onTap: () {
calculator cal = calculator(height: height, weight: weight);
Navigator.push(context, MaterialPageRoute(builder: (context) => results(result: calculator().getresult(), bmi: calculator().calculatebmi(), remarks: calculator().getRemarks())));
},)`
The problem occurs because the value _bmi is null. And it is because you are not calling calculatebmi().
You are calculating BMI with empty parameters of calculator(). So, instead of setting
bmi:calculator().getresult();
use as :
bmi : cal.getresult(); // You already have insteance of calculator (cal)

add an item to a list inside a nested map in Dart/Flutter

When I call addItemToCart({"key": "val"}), I'm having trouble to add the item to a list inside a nested map in Dart/Flutter. var list = cart['items'] gave back me a null, but I initialized class member cart already.
What's really wrong with it?
import 'package:flutter/material.dart';
import 'dart:collection';
class PData extends ChangeNotifier {
dynamic cart = {"items": []};
int itemCount = 0;
String uid;
String phoneNumber;
void addItemToCart(val){
var list = cart['items'];
print("list ");
print (list);
list.add(val);
notifyListeners();
}
}
Gives the following error:
I/flutter ( 5763): list
I/flutter ( 5763): null
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'add' was called on null.
Receiver: null
Tried calling: add(_LinkedHashMap len:6)
You need to add .toList() to initiate. See the sample code snippet below :
var list = cart['items'];
var realList = list.toList();
print("list ");
print (list);
realList.add("soap");
print(realList); // This prints [soap]
realList.add("Pen");
print(realList); // This prints [soap, pen]