Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>unknownk101New to Visual Studio Code? Get it now.
unknownk101

unknownk101

unknownk101

|
3 installs
| (0) | Free
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Flutter-BMI

bmi_app/
 ├─ lib/
 │   ├─ main.dart
 │   └─ BMICalculator.dart   <-- your widget 
 ├─ pubspec.yaml
 └─ android/  ios/  (platform folders)
BMICalculator.dart
// lib/BMICalculator.dart
import 'package:flutter/material.dart';

class BMICalculator extends StatefulWidget {
  const BMICalculator({super.key});

  @override
  State<BMICalculator> createState() => _BMICalculatorState();
}

class _BMICalculatorState extends State<BMICalculator> {
  final TextEditingController heightController = TextEditingController();
  final TextEditingController weightController = TextEditingController();
  double bmiResult = 0.0;

  void calculateBMI() {
    setState(() {
      try {
        final double height = double.parse(heightController.text);
        final double weight = double.parse(weightController.text);

        if (height <= 0 || weight <= 0) {
          throw Exception('Height and weight must be positive numbers');
        }

        bmiResult = weight / (height * height);
      } catch (e) {
        bmiResult = 0.0;
      }
    });
  }

  String _getCategory(double bmi) {
    if (bmi < 18.5) return 'Underweight 😲';
    if (bmi <= 24.9) return 'Normal Weight 😉';
    if (bmi <= 29.9) return 'Overweight 🤒';
    return 'Obese 💀';
  }

  void clearResult() {
    setState(() {
      heightController.clear();
      weightController.clear();
      bmiResult = 0.0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: const Text(
          'BMI Calculator',
          style: TextStyle(color: Colors.white),
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: heightController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: 'Height (m)',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 20),
              TextField(
                controller: weightController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: 'Weight (kg)',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: calculateBMI,
                child: const Text('Calculate BMI'),
              ),
              const SizedBox(height: 12),
              ElevatedButton(
                onPressed: clearResult,
                child: const Text('Clear'),
              ),
              const SizedBox(height: 30),
              bmiResult > 0
                  ? Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.greenAccent,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        children: [
                          Text(
                            'BMI: ${bmiResult.toStringAsFixed(1)}',
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            'You are ${_getCategory(bmiResult)}',
                            style: const TextStyle(fontSize: 20),
                          ),
                        ],
                      ),
                    )
                  : const SizedBox.shrink(),
            ],
          ),
        ),
      ),
    );
  }
}

main.dart
import 'package:flutter/material.dart';
import 'BMICalculator.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'BMI App',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const BMICalculator(),
    );
  }
}

Regi

registration_form/
│
├── lib/
│   ├── main.dart
│   ├── RegistrationForm.dart
│   └── DetailsPage.dart
│
├── pubspec.yaml
│
├── android/        (Auto generated)
├── ios/            (Auto generated)
├── test/
└── build/
lib/main.dart
import 'package:flutter/material.dart';
import 'RegistrationForm.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const RegistrationForm(),
    );
  }
}

lib/RegistrationForm.dart
import 'package:flutter/material.dart';
import 'DetailsPage.dart';

class RegistrationForm extends StatefulWidget {
  const RegistrationForm({super.key});

  @override
  State<RegistrationForm> createState() => _RegistrationFormState();
}

class _RegistrationFormState extends State<RegistrationForm> {
  final TextEditingController nameController = TextEditingController();
  String? gender;
  bool langEnglish = false;
  bool langHindi = false;
  bool langMarathi = false;

  final List<String> cities = ["Mumbai", "Delhi", "Pune"];
  String? selectedCity;

  bool darkBackground = false;

  void onSubmit() {
    List<String> langList = [];
    if (langEnglish) langList.add("English");
    if (langHindi) langList.add("Hindi");
    if (langMarathi) langList.add("Marathi");

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Details(
          name: nameController.text,
          gender: gender ?? "Not selected",
          languages: langList,
          selectedCity: selectedCity,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Registration Form"), backgroundColor: Colors.green),
      body: Container(
        color: darkBackground ? Colors.green[50] : Colors.white,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                TextField(
                  controller: nameController,
                  decoration: const InputDecoration(
                    labelText: "Enter name:",
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 16),
                const Text("Select your gender:"),
                RadioListTile(
                  title: const Text("Male"),
                  value: "Male",
                  groupValue: gender,
                  onChanged: (value) => setState(() => gender = value),
                ),
                RadioListTile(
                  title: const Text("Female"),
                  value: "Female",
                  groupValue: gender,
                  onChanged: (value) => setState(() => gender = value),
                ),
                const SizedBox(height: 16),
                const Text("Select the languages:"),
                CheckboxListTile(
                  title: const Text("English"),
                  value: langEnglish,
                  onChanged: (val) => setState(() => langEnglish = val ?? false),
                ),
                CheckboxListTile(
                  title: const Text("Hindi"),
                  value: langHindi,
                  onChanged: (val) => setState(() => langHindi = val ?? false),
                ),
                CheckboxListTile(
                  title: const Text("Marathi"),
                  value: langMarathi,
                  onChanged: (val) => setState(() => langMarathi = val ?? false),
                ),
                const SizedBox(height: 16),
                DropdownButton(
                  isExpanded: true,
                  value: selectedCity,
                  hint: const Text("Select city"),
                  items: cities.map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(),
                  onChanged: (value) => setState(() => selectedCity = value),
                ),
                SwitchListTile(
                  title: const Text("Dark Background"),
                  value: darkBackground,
                  onChanged: (val) => setState(() => darkBackground = val),
                ),
                const SizedBox(height: 24),
                ElevatedButton(onPressed: onSubmit, child: const Text("Submit")),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

lib/DetailsPage.dart
import 'package:flutter/material.dart';

class Details extends StatelessWidget {
  final String name;
  final String gender;
  final List<String> languages;
  final String? selectedCity;

  const Details({
    super.key,
    required this.name,
    required this.gender,
    required this.languages,
    required this.selectedCity,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Details"), backgroundColor: Colors.blue),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Name: $name"),
            Text("Gender: $gender"),
            Text("Languages: ${languages.isEmpty ? "None" : languages.join(", ")}"),
            Text("City: ${selectedCity ?? "Not selected"}"),
          ],
        ),
      ),
    );
  }
}

crud-fluttersqlite

sqflite_crud/
│
├── lib/
│   ├── main.dart
│   ├── Homepage.dart
│   └── database_helper.dart
│
├── pubspec.yaml
│
├── android/
├── ios/
└── build/
pubspec.yaml (dependencies section)
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.8
  sqflite: ^2.2.0
  path_provider: ^2.0.15
  path: ^1.8.3

lib/main.dart
import 'package:flutter/material.dart';
import 'Homepage.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(),
    );
  }
}

lib/database_helper.dart
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static const _databaseName = "MyDatabase.db";
  static const _databaseVersion = 1;

  static const table = 'my_table';
  static const columnId = '_id';
  static const columnName = 'name';

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database? _database;

  Future<Database> get database async {
    _database ??= await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE $table (
        $columnId INTEGER PRIMARY KEY,
        $columnName TEXT NOT NULL
      )
    ''');
  }

  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await database;
    return await db.insert(table, row);
  }

  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await database;
    return await db.query(table);
  }

  Future<int> update(Map<String, dynamic> row) async {
    Database db = await database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<int> delete(int id) async {
    Database db = await database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}

lib/Homepage.dart

import 'package:flutter/material.dart';
import 'database_helper.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _idController = TextEditingController();
  final _nameController = TextEditingController();

  String _message = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SQLite Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: _idController, decoration: const InputDecoration(labelText: "ID")),
            TextField(controller: _nameController, decoration: const InputDecoration(labelText: "Name")),
            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                final name = _nameController.text.trim();

                if (id == null || name.isEmpty) {
                  setState(() => _message = "Enter valid ID & Name");
                  return;
                }

                await DatabaseHelper.instance.insert({
                  DatabaseHelper.columnId: id,
                  DatabaseHelper.columnName: name,
                });

                _idController.clear();
                _nameController.clear();

                setState(() => _message = "Inserted Successfully");
              },
              child: const Text("Insert"),
            ),

            ElevatedButton(
              onPressed: () async {
                final rows = await DatabaseHelper.instance.queryAllRows();
                setState(() => _message = rows.toString());
              },
              child: const Text("Show"),
            ),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                final name = _nameController.text.trim();
                if (id == null || name.isEmpty) {
                  setState(() => _message = "Enter valid ID & Name");
                  return;
                }
                await DatabaseHelper.instance.update({
                  DatabaseHelper.columnId: id,
                  DatabaseHelper.columnName: name,
                });
                setState(() => _message = "Updated Successfully");
              },
              child: const Text("Update"),
            ),

            ElevatedButton(
              onPressed: () async {
                final id = int.tryParse(_idController.text.trim());
                if (id == null) {
                  setState(() => _message = "Enter valid ID");
                  return;
                }
                await DatabaseHelper.instance.delete(id);
                setState(() => _message = "Deleted Successfully");
              },
              child: const Text("Delete"),
            ),

            const SizedBox(height: 20),
            Text(_message, style: const TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}

rest api

rest_api_app/
│
├── lib/
│   ├── main.dart
│   ├── HomePage.dart
│   ├── User.dart
│   └── Remote_service.dart
│
├── pubspec.yaml
├── android/
├── ios/
└── build/
pubspec.yaml (dependencies)
dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.6

lib/main.dart
import 'package:flutter/material.dart';
import 'HomePage.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

lib/User.dart

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

class User {
  int rno;
  String name;

  User({required this.rno, required this.name});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      rno: json["rno"],
      name: json["name"],
    );
  }
}


lib/Remote_service.dart
import 'package:http/http.dart' as http;
import 'User.dart';

class RemoteService {
  Future<List<User>> getUsers() async {
    final uri = Uri.parse("https://mocki.io/v1/5e56d735-4e27-4afa-b82a-a4c384c42523");

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      return userFromJson(response.body);
    } else {
      return []; // handle safely
    }
  }
}

lib/HomePage.dart
import 'package:flutter/material.dart';
import 'User.dart';
import 'Remote_service.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<User>? users;
  bool isLoaded = false;

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  fetchData() async {
    users = await RemoteService().getUsers();
    setState(() {
      isLoaded = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("REST API Demo")),
      body: isLoaded
          ? (users == null || users!.isEmpty
              ? const Center(child: Text("No data found"))
              : ListView.builder(
                  itemCount: users!.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(users![index].name),
                      subtitle: Text("Rno: ${users![index].rno}"),
                    );
                  }))
          : const Center(child: CircularProgressIndicator()),
    );
  }
}
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft