All Cheatsheets

Flutter

Flutter

Flutter is an open-source UI toolkit from Google, released in 2017, for building natively compiled apps for mobile, web, and desktop from a single codebase. It is written in the Dart language (see the Dart cheatsheet for language basics). Instead of using the platform's native UI controls, Flutter draws every pixel itself with its own rendering engine, so the app looks and behaves the same on every platform.

Key Features -
  • Single Codebase : One Dart codebase compiles to Android, iOS, web, Windows, macOS, and Linux.
  • Everything Is a Widget : The entire UI is built from widgets, small building blocks composed into a tree.
  • Hot Reload : See code changes in the running app in under a second, without losing the app's current state. This makes UI development very fast.
  • Own Rendering Engine : Flutter paints the UI with its Skia/Impeller engine rather than relying on native components, giving pixel-perfect consistency and smooth 60/120fps animations.
  • Native Performance : Dart compiles ahead-of-time to native machine code for release builds.
  • Rich Widget Sets : Material Design (Android style) and Cupertino (iOS style) widgets are built in.

How Flutter Works

Flutter builds the UI as a tree of widgets. When data changes, the affected widgets are rebuilt, and Flutter efficiently updates only what changed on screen, much like React's virtual DOM.

The Build Process -
  • 1. Widget Tree : Your UI is a nested tree of widgets that describe what the interface should look like.
  • 2. build() : Each widget has a build() method that returns its child widgets. Flutter calls it to construct the UI.
  • 3. Three Trees : Flutter keeps a Widget tree (the config), an Element tree (the live instances), and a Render tree (what gets painted). Widgets are cheap and thrown away often; elements persist.
  • 4. setState / Rebuild : When state changes, the affected widgets rebuild, producing a new widget tree.
  • 5. Diff & Paint : Flutter compares the new tree to the old one and repaints only the parts that actually changed.
void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Hello Flutter')), body: Center(child: Text('Welcome!')), ), ); } }

Setup & Commands

The Flutter SDK includes Dart and the flutter command-line tool. You also need a device or emulator to run the app.

flutter --version # check version flutter doctor # check setup and missing dependencies flutter create my_app # create a new project cd my_app flutter devices # list connected devices/emulators flutter run # run the app (press r = hot reload, R = restart) flutter build apk # build Android APK flutter build ios # build for iOS flutter build web # build for web
Packages (pub) -

Dependencies live in pubspec.yaml and come from pub.dev, Dart and Flutter's package registry.

flutter pub get # install dependencies flutter pub add http # add a package flutter pub upgrade # update packages

Project Structure

A Flutter project keeps your Dart code in lib/ and has separate folders for each target platform.

my_app/ ├── lib/ │ ├── main.dart # entry point, runs the app │ ├── screens/ # full-page widgets │ ├── widgets/ # reusable UI pieces │ ├── models/ # data classes │ └── services/ # API calls, business logic ├── android/ # Android-specific files ├── ios/ # iOS-specific files ├── web/ # web-specific files ├── assets/ # images, fonts (declared in pubspec) ├── test/ # test files └── pubspec.yaml # dependencies, assets, project config
  • main.dart : Contains main(), which calls runApp() with the root widget.
  • pubspec.yaml : The manifest: lists packages, assets, fonts, and the app version.

Widgets

In Flutter, everything on screen is a widget: text, buttons, padding, layout, and even the app itself. Widgets are immutable descriptions of part of the UI, composed into a tree. There are two fundamental kinds.

  • StatelessWidget : Has no internal state that changes; it looks the same once built (unless its inputs change). Example: an icon, a label. It only needs a build() method.
  • StatefulWidget : Holds mutable state that can change over time, triggering rebuilds. Example: a checkbox, a counter, a form.
Common Widgets -
  • Text : Displays a string, styled with TextStyle.
  • Image : Shows images from assets, network, or files.
  • Icon : A Material or Cupertino icon.
  • Container : A box for styling: padding, margin, color, borders, size.
  • ElevatedButton / TextButton / IconButton : Tappable buttons with an onPressed callback.
  • Scaffold : The basic page layout providing app bar, body, drawer, and bottom navigation.
  • AppBar : The top bar with title and actions.
  • MaterialApp : The root widget that sets up theming, routing, and Material Design.

Layout Widgets

Layout in Flutter is done by nesting widgets, mainly rows, columns, and boxes, rather than by writing CSS.

  • Column : Arranges children vertically.
  • Row : Arranges children horizontally.
  • Stack : Layers children on top of each other (for overlays and badges).
  • Container : A single child with padding, margin, decoration, and sizing.
  • Padding : Adds space around its child.
  • Center : Centers its child.
  • Expanded / Flexible : Make a child fill available space inside a Row or Column.
  • SizedBox : A fixed-size box, also used as a spacer.
  • ListView : A scrollable list, with ListView.builder for long or dynamic lists.
  • GridView : A scrollable grid of items.
Alignment -
  • mainAxisAlignment : Positions children along the main axis (vertical for Column, horizontal for Row).
  • crossAxisAlignment : Positions children along the other axis.
Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('Title'), SizedBox(height: 10), // spacer Row( children: [ Icon(Icons.star), Expanded(child: Text('fills the rest')), ], ), ], )

State & StatefulWidget

State is data that can change while the app runs and affects what is shown. A StatefulWidget pairs with a State class that holds the data; calling setState() tells Flutter to rebuild the widget with the new values.

class Counter extends StatefulWidget { @override State<Counter> createState() => _CounterState(); } class _CounterState extends State<Counter> { int count = 0; // the state void increment() { setState(() { // triggers a rebuild count++; }); } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: increment, child: Text('Count: $count'), ); } }
  • setState : Always change state inside setState(), or the UI will not update.
  • Lifecycle : initState() runs once when the widget is created (good for setup), and dispose() runs when it is removed (good for cleanup).
  • BuildContext : A handle to the widget's location in the tree, used to access theme, navigation, and inherited data.

State Management

setState works within a single widget, but sharing state across many screens needs a state management solution, so data does not have to be passed down manually through every widget.

  • Provider : The long-recommended, beginner-friendly option built on InheritedWidget. Exposes shared state to the widget tree.
  • Riverpod : A modern, more flexible evolution of Provider, compile-safe and not tied to the widget tree. Popular for new apps.
  • Bloc / Cubit : A structured pattern separating events, business logic, and state. Favored for large, complex apps.
  • GetX : An all-in-one package combining state management, navigation, and dependency injection with minimal code.
  • InheritedWidget : The low-level Flutter mechanism the above tools build on, passing data down the tree efficiently.

Networking & Async

Flutter apps fetch data from APIs using Dart's async features (Future, async/await) and an HTTP package. Because the UI runs on a single thread, network calls must be asynchronous so the app stays responsive.

import 'package:http/http.dart' as http; import 'dart:convert'; Future<List> fetchUsers() async { final res = await http.get(Uri.parse('https://api.example.com/users')); if (res.statusCode == 200) { return jsonDecode(res.body); } throw Exception('Failed to load'); }
  • http / dio : http is the simple official package; dio adds interceptors, timeouts, and more for bigger apps.
  • FutureBuilder : A widget that builds UI based on a Future, showing loading, error, and data states automatically.
  • StreamBuilder : The equivalent for a Stream of values, rebuilding as new data arrives.
  • JSON : Parse responses with jsonDecode, usually into model classes.

Packages & Uses

Flutter's functionality is extended with packages from pub.dev. A few commonly used ones:

  • http / dio : Networking and API calls.
  • provider / riverpod / flutter_bloc : State management.
  • shared_preferences : Store simple key-value data on the device.
  • sqflite / hive / isar : Local databases for structured data.
  • go_router : Declarative routing.
  • firebase_core / cloud_firestore : Firebase backend (auth, database, storage).
  • cached_network_image : Load and cache images from the network.
  • intl : Formatting dates, numbers, and localization.
What Flutter Is Used For -
  • Cross-Platform Mobile Apps : Its main use, building Android and iOS apps from one codebase.
  • Web & Desktop : The same code can target the browser, Windows, macOS, and Linux.
  • MVPs & Startups : Fast development and hot reload make it ideal for shipping quickly.
  • Rich, Custom UIs : Because Flutter draws everything itself, highly branded and animated interfaces are easy.
Flutter vs React Native -

Both build cross-platform apps from one codebase. Flutter uses Dart and draws its own widgets for consistent results and strong performance. React Native uses JavaScript and renders real native components, which feels more platform-native but can be less consistent across devices.