NoSuchMethodError, Exception caught by widgets library - flutter

════════ 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)

Related

The method '>=' was called on null. Receiver: null

So, I figured out that the mistake producing the error is the double _bmi inside the calculateBMI() method. However, I would like to know why including double produces this error? What is the logical process?
import 'dart:math';
class CalculatorBrain {
CalculatorBrain({this.height, this.weight});
final int height;
final int weight;
double _bmi;
String calculateBMI() {
double _bmi = height / pow(height / 100, 2);
return _bmi.toStringAsFixed(1);
}
String getResult() {
if (_bmi >= 25.0) {
return 'Overweight';
} else if (_bmi > 18.5) {
return 'Normal';
} else {
return 'Underweight';
}
}
}
Fron the calculateBMI() function, you have redeclared the _bmi variable double _bmi = height / pow(height / 100, 2);.
It's supposed to be:
_bmi = height / pow(height / 100, 2);

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';
}
}
}

Questions on Flutter DropdownButton Value

Hello I'm new to flutter and I'm trying to create multiple DropdownButtons based on different documents in my Firebase backend. Since there may be multiple DropdownButton (different documents have different number of dropdowns to be created), I wanted to maintain there values with List<String> formInput (formInput[0] maintains the first DropdownButton value etc).
But I keep encountering this error, and came to the conclusion that it is was the formInput[i] fault.
So my question is why can't I use formInput[i] as a value for a Dropdownbutton? Is formInput[i] not considered one item? And is there a better solution for maintaining unknown number of values?
Many Thanks
Code:
class _SubmissionFormState extends State<SubmissionForm> {
List<String> formInput;
var test;
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return FutureBuilder(
future: getStringFromPref('site'),
builder: (context, snapshot) {
if (snapshot.hasData) {
String site = snapshot.data;
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('form')
.where('name', isEqualTo: site)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
int inputSize = snapshot.data.documents.length;
List<Widget> listOfWidget = [];
formInput = new List<String>.filled(inputSize, '-');
print(formInput.length);
for (int i = 0; i < inputSize; i++) {
DocumentSnapshot snap = snapshot.data.documents[i];
List<DropdownMenuItem> options = [];
// adding drop down menu items
for (int j = 0; j < snap['formVal'].length; j++) {
String formVal = snap['formVal'][j];
options.add(DropdownMenuItem(
child: Text(
formVal,
),
value: formVal,
));
print('[inner loop] for loop $i ' + snap['formVal'][j]);
}
// the list of DropdownButtons
listOfWidget.add(DropdownButton(
value: formInput[i],
items: options,
hint: Text(
"-",
),
onChanged: (value) {
setState(() {
formInput[i] = value;
});
},
));
// listOfWidget.add(Text(snap['formTxt']));
}
return Column(
children: listOfWidget,
);
} else {
return CircularProgressIndicator();
}
});
} else {
return CircularProgressIndicator();
}
},
);
}
}
Error:
I/flutter (30860): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30860): The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter (30860): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#60d57):
I/flutter (30860): There should be exactly one item with [DropdownButton]'s value: -.
I/flutter (30860): Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
I/flutter (30860): 'package:flutter/src/material/dropdown.dart':
I/flutter (30860): Failed assertion: line 839 pos 15: 'items == null || items.isEmpty || value == null ||
I/flutter (30860): items.where((DropdownMenuItem<T> item) {
I/flutter (30860): return item.value == value;
I/flutter (30860): }).length == 1'
I/flutter (30860):

Error: The method '>=' was called on null

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).

RangeError (index): Invalid value: Valid value range is empty: 0 (http request)

i'm a beginner in flutter and
i have a problem with my http request, when i wanna add in my DropdownButton this http request (that i put in the list called deviceGet) or even print it to see it : i have this error :
RangeError(index) : Invalid value : Valid value range is empty : 0
This is all the error message :
Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building Builder:
RangeError (index): Invalid value: Valid value range is empty: 0
The relevant error-causing widget was
MaterialApp
package:chat/main.dart:180
When the exception was thrown, this was the stack
#0 List.[] (dart:core-patch/growable_array.dart:149:60)
#1 _MyListScreenState.initState
package:chat/main.dart:226
#2 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4428
#3 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4274
#4 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3269
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 1 of 591 libraries in 363ms.
flutter: 0
════════ Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building Builder:
RangeError (index): Invalid value: Valid value range is empty: 0
The relevant error-causing widget was
MaterialApp
package:chat/main.dart:180
When the exception was thrown, this was the stack
#0 List.[] (dart:core-patch/growable_array.dart:149:60)
#1 _MyListScreenState.initState
package:chat/main.dart:225
#2 StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4428
#3 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4274
#4 Element.inflateWidget
I don't understand this error because i can see my request if i put in the body
ListView.builder(
itemCount: deviceGet.length,
itemBuilder: (context, index) {
return ListTile(
title: Text("Num $index " + device[index].commands[0].id));
title: Text("Num $index " + deviceGet[index].name));
or if i put
Text(deviceGet[0].name)
but with warning
This is my code :
import 'dart:convert';
import 'package:flutter/material.dart';
import 'Get.dart';
import 'Device.dart';
import 'Commands.dart';
import 'deviceData.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}
class MyListScreen extends StatefulWidget {
#override
createState() => _MyListScreenState();
}
class _MyListScreenState extends State {
//
List<deviceData> dataDevice = deviceData.getDevicesData();
List<DropdownMenuItem<deviceData>> listDropDevice;
deviceData deviceSelection;
//
var deviceGet = new List<Device>();
GetDevice() {
GET.getDevice().then((response) {
setState(() {
Iterable list = json.decode(response.body);
deviceGet = list.map((model) => Device.fromJson(model)).toList();
});
});
}
void initState() {
super.initState();
GetDevice();
//print(deviceGet[0].name);
// add in the dropDown
for (int i = 0; i < 5;) {
print(i);
dataDevice.add(deviceData("Device" + i.toString()));
dataDevice.add(deviceData(deviceGet[0].name));
i = i + 1;
}
listDropDevice = buildDropdownMenuItems(dataDevice);
deviceSelection = listDropDevice[0].value;
}
List<DropdownMenuItem<deviceData>> buildDropdownMenuItems(List devices) {
List<DropdownMenuItem<deviceData>> items = List();
for (deviceData device1 in devices) {
items.add(
DropdownMenuItem(
value: device1,
child: Text(device1.name),
),
);
}
return items;
}
onChange(deviceData selectionUtilisateur) {
setState(() {
deviceSelection = selectionUtilisateur;
});
}
#override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("Device List"),
),
body: Column(children: <Widget>[
//Text(deviceGet[0].name),
DropdownButton(
value: deviceSelection,
items: listDropDevice,
onChanged: onChange,
),
]));
}
}
Thank you for you help
GetDevice() is asynchronous method so it takes time to get data from json and in the begging deviceGet is empty, so it gives error of range.
you can make GetDevice() method asynchronous using await and async* and while calling that method use .then method and then access values.
also, make sure that you are getting data in GetDevice metod.
I already had a similar problem.
The Problem is within the for loop.
In place of
for (int i = 0; i < 5;) {
print(i);
dataDevice.add(deviceData("Device" + i.toString()));
dataDevice.add(deviceData(deviceGet[0].name));
i = i + 1;
}
listDropDevice = buildDropdownMenuItems(dataDevice);
deviceSelection = listDropDevice[0].value;
}
change it to
for (int i = 0; i < 5;) {
print(i);
dataDevice.add(deviceData("Device" + i.toString()));
dataDevice.add(deviceData(deviceGet[i].name));
i = i + 1;
}
listDropDevice = buildDropdownMenuItems(dataDevice);
deviceSelection = listDropDevice[i].value;
}