Flutter Cheatsheet

Quick reference for Flutter development

📋 What is a Flutter Cheatsheet?

A Flutter cheatsheet is a quick reference guide containing commonly used widgets, syntax patterns, and code snippets. It helps developers quickly find and implement Flutter features without searching through documentation repeatedly.


// Quick widget example
Container(
  child: Text('Hello'),
)

// Quick navigation
Navigator.push(context, MaterialPageRoute(...))
                                    

Cheatsheet Categories

🧩

Common Widgets

Quick reference for frequently used Flutter widgets. Includes Container, Text, Row, Column, ListView, and other essential building blocks for creating user interfaces.

🎯

State Management

Patterns for managing app state effectively. Covers setState, Provider, Riverpod, and BLoC patterns with simple examples for handling data flow in applications.

🚀

Navigation

Routes and navigation patterns for multi-screen apps. Push, pop, named routes, and passing data between screens with Navigator and routing configurations.

🌐

API & Networking

HTTP requests and data fetching patterns. Make GET, POST requests, parse JSON, handle errors, and integrate REST APIs into your Flutter applications.

🔹 Basic App Structure

Essential boilerplate for Flutter apps:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(child: Text('Hello Flutter!')),
    );
  }
}

🔹 Common Widgets Quick Reference

Most frequently used widgets:

// Text
Text('Hello', style: TextStyle(fontSize: 20))

// Container
Container(width: 100, height: 100, color: Colors.blue)

// Row (horizontal)
Row(children: [Text('A'), Text('B')])

// Column (vertical)
Column(children: [Text('A'), Text('B')])

// Button
ElevatedButton(onPressed: () {}, child: Text('Click'))

// Image
Image.network('url')
Image.asset('assets/image.png')

// Icon
Icon(Icons.home, size: 30, color: Colors.blue)

// ListView
ListView(children: [Text('Item 1'), Text('Item 2')])

// Card
Card(child: Padding(padding: EdgeInsets.all(16), child: Text('Card')))

// TextField
TextField(decoration: InputDecoration(labelText: 'Name'))

// Padding
Padding(padding: EdgeInsets.all(16), child: Text('Padded'))

// Center
Center(child: Text('Centered'))

// Stack (layered)
Stack(children: [Container(), Text('Top')])

// Expanded
Row(children: [Expanded(child: Container())])

// SizedBox (spacing)
SizedBox(height: 20, width: 100)

🔹 StatefulWidget Template

Quick template for stateful widgets:

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State {
  int counter = 0;
  
  void incrementCounter() {
    setState(() {
      counter++;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $counter'),
        ElevatedButton(
          onPressed: incrementCounter,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

🔹 Navigation Patterns

Common navigation code snippets:

// Push to new screen
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => SecondScreen()),
);

// Pop back
Navigator.pop(context);

// Push with data
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => DetailScreen(data: 'Hello'),
  ),
);

// Named routes (in MaterialApp)
MaterialApp(
  routes: {
    '/': (context) => HomeScreen(),
    '/details': (context) => DetailsScreen(),
  },
)

// Navigate to named route
Navigator.pushNamed(context, '/details');

// Replace current screen
Navigator.pushReplacement(
  context,
  MaterialPageRoute(builder: (context) => NewScreen()),
);

// Pop until first route
Navigator.popUntil(context, (route) => route.isFirst);

🔹 HTTP Requests

Making API calls with http package:

import 'package:http/http.dart' as http;
import 'dart:convert';

// GET request
Future fetchData() async {
  final response = await http.get(
    Uri.parse('https://api.example.com/data'),
  );
  
  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    print(data);
  }
}

// POST request
Future postData() async {
  final response = await http.post(
    Uri.parse('https://api.example.com/data'),
    headers: {'Content-Type': 'application/json'},
    body: json.encode({'name': 'John', 'age': 30}),
  );
  
  if (response.statusCode == 201) {
    print('Success');
  }
}

// Parse JSON to model
class User {
  final String name;
  final int age;
  
  User({required this.name, required this.age});
  
  factory User.fromJson(Map json) {
    return User(name: json['name'], age: json['age']);
  }
}

🔹 ListView Patterns

Different ways to create lists:

// Simple ListView
ListView(
  children: [
    ListTile(title: Text('Item 1')),
    ListTile(title: Text('Item 2')),
  ],
)

// ListView.builder (efficient for long lists)
ListView.builder(
  itemCount: 100,
  itemBuilder: (context, index) {
    return ListTile(title: Text('Item $index'));
  },
)

// ListView.separated (with dividers)
ListView.separated(
  itemCount: 20,
  itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
  separatorBuilder: (context, index) => Divider(),
)

// Horizontal ListView
ListView(
  scrollDirection: Axis.horizontal,
  children: [
    Container(width: 100, color: Colors.red),
    Container(width: 100, color: Colors.blue),
  ],
)

🔹 Form Validation

Quick form with validation:

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State {
  final _formKey = GlobalKey();
  String _email = '';
  
  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter email';
              }
              if (!value.contains('@')) {
                return 'Please enter valid email';
              }
              return null;
            },
            onSaved: (value) => _email = value!,
          ),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                _formKey.currentState!.save();
                print('Email: $_email');
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

🔹 Async Operations

Working with Future and async/await:

// Future function
Future fetchUserName() async {
  await Future.delayed(Duration(seconds: 2));
  return 'John Doe';
}

// FutureBuilder widget
FutureBuilder(
  future: fetchUserName(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    }
    if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }
    return Text('Name: ${snapshot.data}');
  },
)

// Multiple futures
Future.wait([
  fetchUserName(),
  fetchUserAge(),
]).then((results) {
  print('Name: ${results[0]}, Age: ${results[1]}');
});

🔹 Common Shortcuts

Useful keyboard shortcuts and commands:

VS Code Shortcuts:

  • stless - Create StatelessWidget
  • stful - Create StatefulWidget
  • Ctrl/Cmd + . - Quick fixes
  • Ctrl/Cmd + Space - Auto-complete
  • Alt + Shift + F - Format code
  • F5 - Run/Debug app
  • Shift + F5 - Stop debugging
  • r - Hot reload (in terminal)
  • R - Hot restart (in terminal)

🔹 Useful Commands

Common Flutter CLI commands:

# Create new project
flutter create my_app

# Run app
flutter run

# Build APK
flutter build apk

# Build iOS
flutter build ios

# Get dependencies
flutter pub get

# Update dependencies
flutter pub upgrade

# Clean build
flutter clean

# Check for issues
flutter doctor

# List devices
flutter devices

# Analyze code
flutter analyze

🧠 Test Your Knowledge

What command creates a new Flutter project?