jayzee
jayzee

Reputation: 225

Flutter double parsing error Invalid double

I'm having trouble with this code which is giving me this error. I'm really new to flutter and this is my first project.

import 'dart:ffi';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BmiCalculator(),
    );
  }
}

//create a statefull widget
class BmiCalculator extends StatefulWidget {
  BmiCalculator({Key key}) : super(key: key);
  @override
  _BmiCalculatorState createState() => _BmiCalculatorState();
}

class _BmiCalculatorState extends State<BmiCalculator> {

  int currentindex = 0;
  double result = 0;
  double height = 0;
  double weight = 0;
  TextEditingController heightController = TextEditingController();
  TextEditingController weightController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text("BMI Calculator", style: TextStyle(color: Colors.black),),
          elevation: 0.0,
          backgroundColor: Color(0xfffafafa),
          actions: [
            IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.settings,
                color: Colors.black,
              )
            )
          ],

        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    radioButton("Man", Colors.blue, 0),
                    radioButton("Woman", Colors.pink, 1),
                  ],
                ),
                SizedBox(
                  height: 20.0 ,
                ),
                Text(
                  "Your Height in CM" ,
                  style: TextStyle(
                    fontSize: 18.0,
                  ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  keyboardType: TextInputType.number,
                  controller: heightController,
                  textAlign: TextAlign.center,
                  decoration: InputDecoration(
                    hintText: "Your Height In CM",
                    filled: true,
                    fillColor: Colors.grey[200],
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: BorderSide.none,
                    ),
                  ),
                ),

                SizedBox(
                  height:20.0,
                ),

                Text(
                  "Your Weight in KG" ,
                  style: TextStyle(
                    fontSize: 18.0,
                  ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  decoration: InputDecoration(
                    hintText: "Your Weight In KG",
                    filled: true,
                    fillColor: Colors.grey[200],
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: BorderSide.none,
                    ),
                  ),
                ),
                SizedBox(height: 20.0,),

                Container(
                  width: double.infinity,
                  height: 50.0,
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        height = double.parse(heightController.value.text);
                        weight = double.parse(weightController.value.text);
                      });
                      calculateBmi(height, weight);
                    },
                    color: Colors.blue,
                    child:Text("Calculate", style: TextStyle(
                      color: Colors.white,
                    )),
                  ),
                ),

                SizedBox(
                  height: 20.0,
                ),

                Container(
                  width: double.infinity,
                  child: Text(
                      "Your BMI is : ",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 24.0,
                        fontWeight: FontWeight.bold,
                      )
                  )
                ),
                SizedBox(
                  height: 50.0,
                ),

                Container(
                    width: double.infinity,
                    child: Text(
                        "$result",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 40.0,
                          fontWeight: FontWeight.bold,
                        )
                    )
                ),
              ],
            ),
          ),
        )
      ),
    );
  }

  
  void calculateBmi(double height, double weight){
    double finalresult = weight / (height * height / 10000);
    double bmi = finalresult;
    setState(() {
      result = bmi;
    });
  }
  
  void changeIndex(int index){
    setState(() {
      currentindex = index;
    });
  }

  Widget radioButton(String value, Color color, int index){
    return Expanded(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 12.0),
        height: 80.0,
        child: FlatButton(
          color: currentindex == index ? color : Colors.grey[200],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),

          onPressed: () {
            changeIndex(index);
          },

          child: Text(value, style: TextStyle(
            color: currentindex == index ? Colors.white : color,
            fontSize: 22.0,
            fontWeight: FontWeight.bold,
          )),
        )
      ),
    );
  }

}

and this is the error:

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════ The following FormatException was thrown while handling a gesture: Invalid double

When the exception was thrown, this was the stack: #0 double.parse (dart:core-patch/double_patch.dart:111:28) #1 _BmiCalculatorState.build.. (package:lab1_flutter/main.dart:129:41) #2 State.setState (package:flutter/src/widgets/framework.dart:1244:30) #3 _BmiCalculatorState.build. (package:lab1_flutter/main.dart:127:23) #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19) ... Handler: "onTap" Recognizer: TapGestureRecognizer#50a78 debugOwner: GestureDetector state: possible won arena finalPosition: Offset(150.6, 444.6) finalLocalPosition: Offset(138.6, 36.6) button: 1 sent tap down ════════════════════════════════════════════════════════════════════════════════════════════════════

Upvotes: 2

Views: 6953

Answers (1)

BabC
BabC

Reputation: 1084

What is happening on line 129 ?

Can you tell us what is displayed by changing this code ?

 setState(() {
  print(heightController.value.text);
  print(weightController.value.text);
  height = double.parse(heightController.value.text);
  weight = double.parse(weightController.value.text);
 });

My guess is that you use heightController in the TextField, but not weightController, so its value is null, so it throw an error when you parse it.

Upvotes: 4

Related Questions