Aplicación de calculadora de IMC más plana

Esto se publicó originalmente en nstack.in
Empezando
Aquí está el video tutorial sobre cómo crear la calculadora de IMC. Si prefiere ver videos, este es el lugar para mirar.
Tutorial de calculadora de IMC
Paso 1
Comencemos la aplicación creando la interfaz de usuario y es simple, pero la dividiré en partes pequeñas para que quede más claro.
Este es el widget que usaré en la aplicación.
- AppBar
- texto
- pilar
- Entrada de texto
- símbolo
- Botón levantado
Construyamos el marco primero, luego profundicemos.
Aplicación de Skelton
paso 2
Convirtamos el esqueleto en la aplicación Flutter.
return Scaffold(
appBar: AppBar(
title: Text('BMI Calculator'),
centerTitle: true,
backgroundColor: Colors.pinkAccent,
),
body: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
labelText: 'Weight in cm',
icon: Icon(Icons.trending_up),
),
),
SizedBox(height: 20),
TextField(
decoration: InputDecoration(
labelText: 'Weight in kg',
icon: Icon(Icons.line_weight),
),
),
SizedBox(height: 15),
RaisedButton(
color: Colors.pinkAccent,
child: Text(
"Calculate",
style: TextStyle(color: Colors.white),
),
onPressed: () ,
),
SizedBox(height: 15),
Text(
"Result will be here" ,
style: TextStyle(
color: Colors.redAccent,
fontSize: 19.4,
fontWeight: FontWeight.w500,
),
),
],
)
La interfaz de usuario del código anterior se AGREGA AQUÍ
paso 3
Ahora vinculamos el controlador de entrada al campo Peso y altura. Nos ayudará a sacar valor del campo.
final TextEditingController _heightController = TextEditingController();
final TextEditingController _weightController = TextEditingController();
Ahora hemos definido dos controladores para dos campos de texto. Deje que se agregue al campo de texto respectivo para que podamos tener control sobre el campo de texto.
TextField(
controller: _heightController, // Added
decoration: InputDecoration(
labelText: 'height in cm',
icon: Icon(Icons.trending_up),
),
),
Agreguemos también el peso.
TextField(
controller: _weightController, // Added
decoration: InputDecoration(
labelText: 'weight in kg',
icon: Icon(Icons.line_weight),
),
),
Paso 4
Ahora escribimos la función en la calculadora BMI y agregamos el evento con un evento de clic. Entonces, cuando hacemos clic en el botón, se calcula el IMC.
Déjame mostrarte la fórmula primero, luego agregaremos esto a nuestro archivo demo.dart
basado en nuestro caso.
/*
@params heigh is in Meter
@params weight is in Kilogram
*/
double calculateBMI(double height, double weight)
double heightSquare = height * height;
double result = weight / heightSquare;
return result;
El código anterior es de referencia para que conozca la fórmula del IMC (en caso de que no lo sepa).
void calculateBMI()
double height = double.parse(_heightController.text) / 100;
double weight = double.parse(_weightController.text);
// We dived height by 100 because we are taking the height in centimeter
// and formula takes height in meter.
double heightSquare = height * height;
double result = weight / heightSquare;
print(result);
Agreguemos el método al hacer clic o presionar el botón.
RaisedButton(
color: Colors.pinkAccent,
child: Text(
"Calculate",
style: TextStyle(color: Colors.white),
),
onPressed: calculateBMI,
),
PASO 5
En el paso anterior hicimos la calculadora de IMC que funciona, pero hay un problema. La aplicación muestra el resultado en la consola y lo queremos en la aplicación.
double _result; // new variable defined for result
void calculateBMI()
double height = double.parse(_heightController.text) / 100;
double weight = double.parse(_weightController.text);
// We dived height by 100 because we are taking the height in centimeter
// and formula takes height in meter.
double heightSquare = height * height;
double result = weight / heightSquare;
print(result);
// setState will update the UI
setState(()
result = result;
);
Todavía nos falta una cosa, nunca llamamos a la variable de resultado en la interfaz de usuario. Acabamos de definir la variable de resultado. Si esto se hubiera llamado antes, sería una injusticia para el lector.
Text(
_result == null ? "Enter Value" : "BMI : $_result",
style: TextStyle(
color: Colors.redAccent,
fontSize: 19.4,
fontWeight: FontWeight.w500,
),
),
Paso 6
En este paso, limitaremos los dos dígitos después del punto decimal para que se vean consistentes y no rompan la interfaz de usuario.
El código anterior es bueno y todo funciona bien, pero hay un problema de interfaz de usuario que el usuario enfrentará algún día.
Existe otro problema de que el valor decimal puede ser muy largo, es decir, puede haber 2 dígitos después del lugar decimal u 8 dígitos después del lugar decimal.
Hagamos que la interfaz de usuario sea coherente haciendo cambios simples.
Text(
_result == null ? "Enter Value" : "BMI : $_result.toStringAsFixed(2)",
style: TextStyle(
color: Colors.redAccent,
fontSize: 19.4,
fontWeight: FontWeight.w500,
),
),
toStringAsFixed
Permítanos limitar el número de dígitos después del decimal.
Conclusión
Divido todo en pedazos pequeños para que sea fácil de seguir. Avísame si puedo hacer esto o no, o si todavía tienes problemas para entenderlo.
Si eres principiante y lo entiendes todo, es realmente bueno porque aprenderás muchas cosas importantes.
- Entrada de texto
- Controles de entrada de texto
- Método de invocación
- Actualizar la interfaz de usuario
También puedes compartir los comentarios en el comentario o tuitear sobre eso (no olvides etiquetar @nstack_in).
Código fuente completo
El código fuente completo también se puede encontrar en Github, pero el código no es muy grande, así que lo puse aquí también.
import 'package:flutter/material.dart';
import 'demo.dart';
void main()
runApp(MyApp());
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.pinkAccent,
),
home: Demo(),
);
import 'package:flutter/material.dart';
class Demo extends StatefulWidget
@override
_DemoState createState() => _DemoState();
class _DemoState extends State<Demo>
final TextEditingController _heightController = TextEditingController();
final TextEditingController _weightController = TextEditingController();
double _result;
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text('BMI Calculator'),
centerTitle: true,
backgroundColor: Colors.pinkAccent,
),
body: Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _heightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'height in cm',
icon: Icon(Icons.trending_up),
),
),
SizedBox(height: 20),
TextField(
controller: _weightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'weight in kg',
icon: Icon(Icons.line_weight),
),
),
SizedBox(height: 15),
RaisedButton(
color: Colors.pinkAccent,
child: Text(
"Calculate",
style: TextStyle(color: Colors.white),
),
onPressed: calculateBMI,
),
SizedBox(height: 15),
Text(
_result == null ? "Enter Value" : "$_result.toStringAsFixed(2)",
style: TextStyle(
color: Colors.redAccent,
fontSize: 19.4,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
void calculateBMI()
double height = double.parse(_heightController.text) / 100;
double weight = double.parse(_weightController.text);
double heightSquare = height * height;
double result = weight / heightSquare;
_result = result;
setState(() );