0
0
Fluttermobile~5 mins

Variables and type inference in Flutter

Choose your learning style9 modes available
Introduction

Variables store information you want to use later. Type inference lets the computer guess the kind of data automatically, so you write less code.

When you want to remember a user's name in your app.
When you need to keep track of a score in a game.
When you want to store a color or size for a button.
When you want to hold a list of items to show on the screen.
Syntax
Flutter
var name = 'Alice';
int age = 30;
double height = 1.75;
String greeting = 'Hello!';

var lets Dart guess the type from the value you give.

You can also write the type explicitly like int or String.

Examples
Dart guesses city is a String because of the quotes.
Flutter
var city = 'Paris';
Here, we say count is an int number explicitly.
Flutter
int count = 5;
Dart infers price as a double because of the decimal point.
Flutter
var price = 9.99;
We tell Dart message is a String directly.
Flutter
String message = 'Welcome!';
Sample App

This app shows how to use variables with and without type inference. It displays the user's name, age, and height on the screen.

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

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

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

  @override
  Widget build(BuildContext context) {
    var userName = 'Sam'; // Dart infers String
    int userAge = 25; // Explicit int
    var userHeight = 1.82; // Dart infers double

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Variables Example')),
        body: Center(
          child: Text('Name: $userName, Age: $userAge, Height: $userHeight m'),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Once a variable's type is set or inferred, you cannot assign a different type to it later.

Using var is handy for quick coding, but explicit types can help avoid mistakes.

Summary

Variables hold data you want to use later in your app.

Type inference lets Dart guess the variable type from the value you give.

You can also write the type explicitly for clarity.