Here’s a Flutter Dev Development CheatSheet to help you with key concepts, commands, and code snippets:
1. Flutter CLI Commands
- Create a new project:
flutter create my_app - Run the app:
flutter run -d chrome - Build the app:
- Android APK:
flutter build apk | appbundle - iOS:
flutter build ios
- Android APK:
- Check devices:
flutter devices - Clean the project:
flutter clean - Upgrade Flutter SDK:
flutter upgrade - Check environment setup:
flutter doctor
2. Basic Project Structure
lib/
├── main.dart # Entry point
├── screens/ # App screens (pages)
├── common/ # Common items - repositories, routing, di, etc
├── widgets/ # Custom widgets
├── models/ # Data models
└── services/ # Business logic or API calls
3. Main Entry Point
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!')),
);
}
}
Here’s an expanded section on 4. Common Widgets to help you build beautiful Flutter UIs efficiently:
🎯 4. Common Widgets in Flutter
1️⃣ Text Widget
- Basic Usage:
Displays a string of text with customizable styling.Text( 'Hello, Flutter!', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.blue, letterSpacing: 1.5, decoration: TextDecoration.underline, ), textAlign: TextAlign.center, ); - Key Properties:
style: Customize font, color, spacing.textAlign: Align text (center,left,right).overflow: Handle long text (ellipsis,fade,clip).maxLines: Limit number of lines.
2️⃣ Buttons
🔹 ElevatedButton
ElevatedButton(
onPressed: () => print('Button Pressed'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
child: Text('Click Me'),
);
🔸 OutlinedButton
OutlinedButton(
onPressed: () {},
child: Text('Outline Button'),
style: OutlinedButton.styleFrom(
side: BorderSide(color: Colors.blue, width: 2),
shape: StadiumBorder(),
),
);
🔹 TextButton
TextButton(
onPressed: () {},
child: Text('Flat Button'),
);
- Bonus Tip: Use
IconButtonfor icon-only buttons:IconButton( icon: Icon(Icons.favorite, color: Colors.red), onPressed: () {}, );
3️⃣ Image Widget
- From Network:
Image.network( 'https://example.com/image.png', width: 200, height: 200, fit: BoxFit.cover, ); - From Assets:
Add the image topubspec.yaml:assets: - assets/images/logo.pngImage.asset('assets/images/logo.png'); - Key Properties:
fit: Controls how the image fits (cover,contain,fill,fitWidth).color: Apply color filters.
4️⃣ Container
A flexible box for layout, styling, and positioning.
Container(
padding: EdgeInsets.all(16),
margin: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(0, 4),
),
],
),
child: Text('Styled Container'),
);
- Key Properties:
padding/margindecoration: Background color, border, gradient, shadows.
5️⃣ Row & Column (Layouts)
Column Example:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
);
Row Example:
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.home),
Icon(Icons.favorite),
Icon(Icons.settings),
],
);
- Key Properties:
mainAxisAlignment: Align along the main axis (center,spaceEvenly,spaceBetween).crossAxisAlignment: Align along the cross-axis (start,end,stretch).
6️⃣ ListView (Scrollable Lists)
Simple List:
ListView(
children: [
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
],
);
Dynamic List (Builder):
ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.star),
title: Text('Item $index'),
);
},
);
- Bonus: For horizontal lists:
ListView.builder( scrollDirection: Axis.horizontal, itemCount: 5, itemBuilder: (context, index) => Container( width: 100, color: Colors.teal, margin: EdgeInsets.all(8), child: Center(child: Text('Card $index')), ), );
7️⃣ Card Widget
Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text('I am a Card'),
),
);
- Use Cases: Displaying grouped content like user profiles, articles, or settings.
8️⃣ Stack & Positioned (Overlapping Widgets)
Stack(
children: [
Container(width: 200, height: 200, color: Colors.blue),
Positioned(
top: 50,
left: 50,
child: Icon(Icons.star, size: 50, color: Colors.white),
),
],
);
- Tip: Use
Aligninstead ofPositionedfor responsive layouts.
9️⃣ Form & TextField (User Input)
TextField:
TextField(
decoration: InputDecoration(
labelText: 'Enter your name',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
);
Form with Validation:
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) => value!.isEmpty ? 'Please enter text' : null,
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Form is valid');
}
},
child: Text('Submit'),
),
],
),
);
🔟 Switch & Checkbox (Toggles)
Switch:
bool isOn = false;
Switch(
value: isOn,
onChanged: (value) {
setState(() {
isOn = value;
});
},
);
Checkbox:
bool isChecked = false;
Checkbox(
value: isChecked,
onChanged: (value) {
setState(() {
isChecked = value!;
});
},
);
Bonus: Custom Widget Example
class CustomCard extends StatelessWidget {
final String title;
final IconData icon;
const CustomCard({required this.title, required this.icon});
@override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: ListTile(
leading: Icon(icon, size: 30),
title: Text(title),
),
);
}
}
Use it like this:
CustomCard(title: 'Flutter is Awesome!', icon: Icons.star);
5. State Management (setState Example)
class CounterApp extends StatefulWidget {
@override
_CounterAppState createState() => _CounterAppState();
}
class _CounterAppState extends State<CounterApp> {
int counter = 0;
void increment() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(child: Text('$counter')),
floatingActionButton: FloatingActionButton(
onPressed: increment,
child: Icon(Icons.add),
),
);
}
}
6. Navigation Between Screens
- Navigate to another screen:
Navigator.push( context, MaterialPageRoute(builder: (context) => SecondScreen()), ); - Go back:
Navigator.pop(context);
7. Handling User Input (Forms & TextFields)
TextEditingController _controller = TextEditingController();
TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Enter text'),
);
ElevatedButton(
onPressed: () {
print(_controller.text);
},
child: Text('Submit'),
);
8. HTTP Requests (Using http Package)
- Add dependency in
pubspec.yaml:dependencies: http: ^0.13.4 - Use in code:
import 'package:http/http.dart' as http; import 'dart:convert'; Future<void> fetchData() async { final response = await http.get(Uri.parse('https://api.example.com/data')); if (response.statusCode == 200) { var data = jsonDecode(response.body); print(data); } else { throw Exception('Failed to load data'); } }
9. Working with JSON
String jsonString = '{"name": "John", "age": 30}';
Map<String, dynamic> user = jsonDecode(jsonString);
print(user['name']); // John
String jsonOut = jsonEncode({'city': 'Sofia', 'population': 1200000});
print(jsonOut);
10. Useful Extensions for VS Code / Android Studio
- Flutter & Dart Plugins
- Flutter Snippets
- Pubspec Assist
- Material Icon Theme
Here’s an expanded section on Performance Tips for Flutter development to help you build faster, more efficient apps:
🚀 11. Performance Tips for Flutter
1. Use const Constructors Wherever Possible
- Why: Reduces widget rebuilds since
constwidgets are immutable and Flutter reuses them. - Example:
// Before: This rebuilds unnecessarily Text('Hello World'); // After: Optimized with const const Text('Hello World'); - Tip: Use
constfor widgets without dynamic data. VS Code can suggest this automatically (look for quick fixes).
2. Optimize List Views
- Problem: Large lists can cause jank (lag).
- Solution: Use
ListView.builderinstead ofListViewbecause it lazily builds items as they scroll into view.ListView.builder( itemCount: 1000, itemBuilder: (context, index) { return ListTile(title: Text('Item $index')); }, ); - Bonus: Use
itemExtentorprototypeItemto improve performance further if item heights are consistent.ListView.builder( itemExtent: 80, // Fixed height improves performance itemCount: 1000, itemBuilder: (context, index) => ListTile(title: Text('Item $index')), );
3. Avoid Unnecessary Widget Rebuilds
- Use
const+ Extract Widgets: Break UI into smaller stateless widgets to isolate rebuilds. - Use
ValueListenableBuilderfor Simple State:ValueNotifier<int> counter = ValueNotifier(0); ValueListenableBuilder<int>( valueListenable: counter, builder: (context, value, _) { return Text('Counter: $value'); }, ); - Optimize with
shouldRebuild: ForCustomPainterorInheritedWidget, overrideshouldRebuildto returnfalsewhen no changes are needed.
4. Leverage RepaintBoundary
- What it does: Isolates parts of the widget tree that don’t need to repaint frequently.
- When to use: For complex animations or heavy UI elements like graphs, maps, etc.
RepaintBoundary( child: HeavyWidget(), // This widget won’t repaint unless necessary ); - Debug Tip: Enable repaint visuals to spot unnecessary repaints:
flutter run --profile --track-widget-creation
5. Use Lazy Loading for Images
- Problem: Loading many high-resolution images can cause memory issues.
- Solution: Use
CachedNetworkImageorFadeInImagewith placeholders.FadeInImage.assetNetwork( placeholder: 'assets/placeholder.png', image: 'https://example.com/image.jpg', ); - Bonus: Use
cacheWidthandcacheHeightto load appropriately sized images.Image.network( 'https://example.com/image.jpg', width: 300, height: 200, cacheWidth: 300, cacheHeight: 200, );
6. Efficient State Management
- Use lightweight solutions:
Provider,Riverpod, orBlocefficiently handle state without unnecessary rebuilds. - Example (with
Provider):ChangeNotifierProvider( create: (_) => CounterModel(), child: Consumer<CounterModel>( builder: (context, counter, _) => Text('${counter.value}'), ), ); - Tip: Use
Selector(with Provider) to rebuild only parts of the UI.Selector<CounterModel, int>( selector: (_, model) => model.value, builder: (_, value, __) => Text('$value'), );
7. Optimize Animations
- Use
AnimatedBuilderorAnimatedWidgetto rebuild only necessary parts.class SpinAnimation extends StatelessWidget { final AnimationController controller; SpinAnimation({required this.controller}); @override Widget build(BuildContext context) { return AnimatedBuilder( animation: controller, builder: (_, child) { return Transform.rotate( angle: controller.value * 6.28, child: child, // Child won't rebuild ); }, child: Icon(Icons.refresh), ); } } - Profile Animations:
flutter run --profile
It is popular to use some implementation of cached network image
8. Reduce Overdraw
- Overdraw happens when pixels are painted multiple times unnecessarily.
- Debug overdraw:
flutter run --profile --show-surface-updates - Fixes:
- Use
Container(color: Colors.transparent)instead of nesting empty containers. - Use
ClipRect,ClipPathwisely as they are expensive.
- Use
9. Efficient Data Handling
- Debounce Text Input:
Reduces API calls when typing in search fields.Timer? _debounce; void onSearchChanged(String query) { if (_debounce?.isActive ?? false) _debounce!.cancel(); _debounce = Timer(Duration(milliseconds: 300), () { // Trigger search }); } - Batch API Calls: Combine API requests if possible, reducing the number of network hits.
10. Build in Release Mode for Production
- Why: Debug mode has performance overhead. Always build in release mode for production testing.
flutter build apk --release flutter run --release - Tip: Use
flutter profilemode to measure performance without full release optimizations.
📊 Bonus: Debugging Performance Issues
- DevTools (Flutter Inspector):
flutter pub global activate devtools flutter pub global run devtools - Performance Overlay:
MaterialApp( showPerformanceOverlay: true, home: HomePage(), );
