iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Cheatsheet

Flutter cheatsheet: widgets, layout, state, navigation, networking.

Flutter — cheatsheet

EXAMPLE
// ===== App scaffold =====
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) => MaterialApp(
    home: Scaffold(appBar: AppBar(title: const Text('Hello')), body: const Center(child: Text('World'))),
  );
}

// ===== Layout widgets =====
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [...])
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [...])
Stack(children: [Positioned(bottom: 0, left: 0, child: ...)])
Expanded(child: ...)
Flexible(flex: 2, child: ...)
SizedBox(width: 16, height: 16)
Padding(padding: const EdgeInsets.all(16), child: ...)
Container(width: 100, height: 100, decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: Colors.blue))
SafeArea(child: ...)
Center(child: ...)

// ===== Text + theme =====
Text('Hello', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold))
Text('Themed', style: Theme.of(context).textTheme.headlineMedium)

// ===== Lists =====
ListView.builder(itemCount: n, itemBuilder: (ctx, i) => ListTile(title: Text(items[i])))
ListView.separated(itemCount: n, separatorBuilder: (_, __) => const Divider(), itemBuilder: ...)
GridView.builder(gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), ...)

// ===== Buttons =====
ElevatedButton(onPressed: () {}, child: const Text('Save'))
TextButton(onPressed: () {}, child: const Text('Cancel'))
OutlinedButton(onPressed: () {}, child: const Text('Outlined'))
IconButton(onPressed: () {}, icon: const Icon(Icons.menu))

// ===== State =====
class MyW extends StatefulWidget { ... }
class _MyWState extends State<MyW> {
  int n = 0;
  void inc() => setState(() => n++);
}

// State management options:
// - Provider / Riverpod (modern; recommended)
// - Bloc (event-driven)
// - GetX (controversial; powerful)

// ===== Navigation =====
// Imperative:
Navigator.of(context).push(MaterialPageRoute(builder: (_) => const DetailPage()));
Navigator.of(context).pop(returnValue);

// Declarative (go_router):
context.go('/detail/42');
context.push('/detail/42');

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

final r = await http.get(Uri.parse('https://api.example.com/users'));
final users = jsonDecode(r.body) as List;

// dio is a popular alternative with interceptors.

// ===== Forms =====
final _formKey = GlobalKey<FormState>();
Form(
  key: _formKey,
  child: Column(children: [
    TextFormField(decoration: const InputDecoration(labelText: 'Email'),
      validator: (v) => (v?.contains('@') ?? false) ? null : 'Invalid'),
    ElevatedButton(onPressed: () { if (_formKey.currentState!.validate()) {/* submit */} },
      child: const Text('Save')),
  ]),
);

// ===== Async UI =====
FutureBuilder(future: fetch(), builder: (ctx, snap) {
  if (!snap.hasData) return const CircularProgressIndicator();
  return Text(snap.data!);
});

StreamBuilder(stream: stream(), builder: (ctx, snap) { ... });

// ===== Persistence =====
// shared_preferences for small key-value
// hive / isar for richer local storage
// sqflite for SQLite

// ===== Animations =====
AnimatedContainer(duration: const Duration(milliseconds: 300), color: c)
Hero(tag: 'image', child: Image.network('...'))

// ===== Build for prod =====
flutter build apk --release
flutter build appbundle --release
flutter build ios --release
flutter build web --release

// ===== Patterns =====
// - const constructors for free perf
// - ListView.builder for lazy lists
// - One state library per app
// - flutter analyze in CI

// ===== Pitfalls =====
// - Heavy build() methods (extract widgets)
// - Forgetting to dispose controllers
// - Using setState for app-wide state
// - Skipping const constructors (avoidable rebuilds)

Why it matters

Flutter cheatsheet: layout widgets, lists, buttons, state, navigation, networking, forms, async UI. Pin this during a build session and most screens come together quickly.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// flutter create | run | pub get | analyze | build | doctor
Try it Yourself »

Discussion

Loading…