0
0
Fluttermobile~20 mins

Variables and type inference in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Variable Demo Screen
This screen shows how to declare variables with and without type inference in Flutter. It displays two texts: one showing a variable declared with explicit type and another with inferred type.
Target UI
-------------------------
| Variable Demo Screen   |
|-----------------------|
| Explicit type: 42     |
| Inferred type: Hello  |
|                       |
|-----------------------|
Display a Scaffold with an AppBar titled 'Variable Demo Screen'.
Show two Text widgets in a Column centered vertically and horizontally.
First Text shows an integer variable declared with explicit type.
Second Text shows a string variable declared with type inference (var).
Starter Code
Flutter
import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    // TODO: Declare variables and build UI
    return Scaffold(
      appBar: AppBar(
        title: const Text('Variable Demo Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // TODO: Add Text widgets here
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    int explicitNumber = 42;
    var inferredString = 'Hello';

    return Scaffold(
      appBar: AppBar(
        title: const Text('Variable Demo Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Explicit type: $explicitNumber'),
            Text('Inferred type: $inferredString'),
          ],
        ),
      ),
    );
  }
}

We declared explicitNumber with the type int explicitly. This means we tell Flutter this variable will hold an integer.

We declared inferredString with var, so Flutter figures out the type automatically from the assigned value, which is a string.

Both variables are then shown in two Text widgets inside a centered Column. This helps beginners see how type declaration and inference work in Flutter.

Final Result
Completed Screen
-------------------------
| Variable Demo Screen   |
|-----------------------|
| Explicit type: 42     |
| Inferred type: Hello  |
|                       |
|-----------------------|
The screen shows two lines of text centered vertically and horizontally.
No user interaction is needed; this is a static display.
Stretch Goal
Add a FloatingActionButton that changes the inferred string to 'Hi Flutter!' when pressed.
💡 Hint
Use a StatefulWidget and setState to update the variable and refresh the UI.