Flutter Cheat Sheet
Complete reference guide for Flutter with interactive examples and live playground links
Click on any section to jump directly to it
Getting Started
Installation
Setting up Flutter development environment
Flutter
# Download Flutter SDK from flutter.dev
# Add Flutter to your path
export PATH="$PATH:[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin"
# Verify installation
flutter doctor
# Create a new project
flutter create my_app
# Run the app
cd my_app
flutter run
Project Structure
Basic structure of a Flutter project
Flutter
my_app/
├── android/ # Android-specific code
├── ios/ # iOS-specific code
├── lib/ # Dart code
│ └── main.dart # Entry point
├── test/ # Test files
├── pubspec.yaml # Project configuration
└── pubspec.lock # Package dependency lock file
Basic App
Basic Flutter application structure
Flutter
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Widgets
Basic Widgets
Common Flutter widgets
Flutter
// Text widget
Text(
'Hello, Flutter!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
)
// Button widgets
ElevatedButton(
onPressed: () {
// Action
},
child: Text('Elevated Button'),
)
TextButton(
onPressed: () {
// Action
},
child: Text('Text Button'),
)
OutlinedButton(
onPressed: () {
// Action
},
child: Text('Outlined Button'),
)
// Image widgets
Image.asset(
'assets/images/logo.png',
width: 200,
height: 200,
)
Image.network(
'https://example.com/image.jpg',
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return CircularProgressIndicator();
},
)
// Icon widget
Icon(
Icons.favorite,
color: Colors.red,
size: 24,
)
// Input widgets
TextField(
decoration: InputDecoration(
labelText: 'Username',
hintText: 'Enter your username',
border: OutlineInputBorder(),
),
onChanged: (value) {
// Handle text change
},
)
// Checkbox and Switch
Checkbox(
value: true,
onChanged: (value) {
// Handle change
},
)
Switch(
value: true,
onChanged: (value) {
// Handle change
},
)
Layout Widgets
Layout widgets for organizing UI
Flutter
// Container
Container(
width: 200,
height: 200,
padding: EdgeInsets.all(16),
margin: EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 5,
offset: Offset(0, 2),
),
],
),
child: Text('Container'),
)
// Row and Column
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(Icons.star),
Icon(Icons.star),
Icon(Icons.star),
],
)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
)
// Stack
Stack(
children: [
Image.asset('assets/background.jpg'),
Positioned(
bottom: 10,
right: 10,
child: Text('Overlay Text'),
),
],
)
// Expanded and Flexible
Row(
children: [
Expanded(
flex: 2,
child: Container(color: Colors.red),
),
Expanded(
flex: 1,
child: Container(color: Colors.blue),
),
],
)
// Wrap
Wrap(
spacing: 8,
runSpacing: 8,
children: [
Chip(label: Text('Flutter')),
Chip(label: Text('Dart')),
Chip(label: Text('Mobile')),
Chip(label: Text('App')),
],
)
List Widgets
Widgets for displaying lists and grids
Flutter
// ListView
ListView(
children: [
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
subtitle: Text('View the map'),
trailing: Icon(Icons.arrow_forward),
onTap: () {
// Handle tap
},
),
ListTile(
leading: Icon(Icons.photo),
title: Text('Photos'),
subtitle: Text('View your photos'),
trailing: Icon(Icons.arrow_forward),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
subtitle: Text('Make a call'),
trailing: Icon(Icons.arrow_forward),
),
],
)
// ListView.builder
ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(
title: Text('Item $index'),
);
},
)
// GridView
GridView.count(
crossAxisCount: 2,
children: List.generate(8, (index) {
return Card(
child: Center(
child: Text('Item $index'),
),
);
}),
)
// GridView.builder
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemCount: 20,
itemBuilder: (context, index) {
return Container(
color: Colors.blue,
child: Center(
child: Text('$index'),
),
);
},
)
State Management
StatefulWidget
Managing state with StatefulWidget
Flutter
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Count: $_counter'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
Provider
State management with Provider package
Flutter
// Add dependency in pubspec.yaml
// provider: ^6.0.0
// Create a model
import 'package:flutter/foundation.dart';
class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// Setup provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MyApp(),
),
);
}
// Use the provider
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Count:',
style: TextStyle(fontSize: 20),
),
// Listen to the provider
Consumer<CounterModel>(
builder: (context, counter, child) {
return Text(
'${counter.count}',
style: TextStyle(fontSize: 40),
);
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Access the provider
Provider.of<CounterModel>(context, listen: false).increment();
},
child: Icon(Icons.add),
),
);
}
}
Navigation
Basic Navigation
Screen navigation in Flutter
Flutter
// Navigate to a new screen
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
// Navigate back
Navigator.pop(context);
// Navigate and replace current screen
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
);
// Navigate and remove all previous screens
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
(route) => false,
);
// Named routes
// In MaterialApp
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
'/settings': (context) => SettingsScreen(),
},
);
// Navigate using named routes
Navigator.pushNamed(
context,
'/details',
arguments: {'id': 123, 'title': 'Item Details'},
);
// Access route arguments
final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
final id = args['id'];
final title = args['title'];
Asynchronous Programming
Future & Async/Await
Working with asynchronous operations
Flutter
// Using Future
Future<String> fetchData() {
return Future.delayed(Duration(seconds: 2), () {
return 'Data loaded';
});
}
// Using async/await
Future<void> loadData() async {
try {
final result = await fetchData();
print(result);
} catch (e) {
print('Error: $e');
}
}
// FutureBuilder
FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Data: ${snapshot.data}');
}
},
)
HTTP Requests
Making HTTP requests in Flutter
Flutter
// Add dependency in pubspec.yaml
// http: ^0.13.4
import 'dart:convert';
import 'package:http/http.dart' as http;
// GET request
Future<List<dynamic>> fetchPosts() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load posts');
}
}
// POST request
Future<Map<String, dynamic>> createPost(String title, String body) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
'body': body,
'userId': '1',
}),
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to create post');
}
}
// Using in a widget
class PostsScreen extends StatefulWidget {
@override
_PostsScreenState createState() => _PostsScreenState();
}
class _PostsScreenState extends State<PostsScreen> {
late Future<List<dynamic>> futurePosts;
@override
void initState() {
super.initState();
futurePosts = fetchPosts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Posts')),
body: FutureBuilder<List<dynamic>>(
future: futurePosts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final post = snapshot.data![index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);
},
);
}
},
),
);
}
}
Flutter - Interactive Developer Reference
Hover over code blocks to copy or run in live playground