実装
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(BMICalculatorApp());
}
class BMICalculatorApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: BMICalculatorScreen(),
);
}
}
class BMICalculatorScreen extends StatefulWidget {
@override
_BMICalculatorScreenState createState() => _BMICalculatorScreenState();
}
class _BMICalculatorScreenState extends State<BMICalculatorScreen> {
TextEditingController heightController = TextEditingController();
TextEditingController weightController = TextEditingController();
String bmiResult = "";
String bmiCategory = "";
void calculateBMI() {
double height = double.tryParse(heightController.text) ?? 0.0;
double weight = double.tryParse(weightController.text) ?? 0.0;
if (height > 0 && weight > 0) {
double bmi = weight / ((height / 100) * (height / 100));
setState(() {
bmiResult = bmi.toStringAsFixed(2);
bmiCategory = getBMICategory(bmi);
});
} else {
setState(() {
bmiResult = "";
bmiCategory = "";
});
}
}
String getBMICategory(double bmi) {
if (bmi < 18.5) {
return "Underweight";
} else if (bmi >= 18.5 && bmi < 24.9) {
return "Normal";
} else if (bmi >= 25 && bmi < 29.9) {
return "Overweight";
} else {
return "Obese";
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BMI Calculator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: heightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Height (cm)',
),
),
SizedBox(height: 16.0),
TextField(
controller: weightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Weight (kg)',
),
),
SizedBox(height: 16.0),
ElevatedButton(
onPressed: calculateBMI,
child: Text('Calculate BMI'),
),
SizedBox(height: 16.0),
Text(
'BMI: $bmiResult',
style: TextStyle(fontSize: 24.0),
),
Text(
'Category: $bmiCategory',
style: TextStyle(fontSize: 18.0),
),
],
),
),
);
}
}