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

Examples

Eight small Flutter examples covering layout, state, navigation, networking, persistence.

Flutter — examples

EXAMPLE
// ===== 1. Hello card =====
import 'package:flutter/material.dart';

class HelloCard extends StatelessWidget {
  const HelloCard({super.key});
  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [Text('Hello'), Text('Flutter')],
        ),
      ),
    );
  }
}

// ===== 2. Counter with state =====
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int n = 0;
  @override
  Widget build(BuildContext context) => Center(
    child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Text('$n', style: const TextStyle(fontSize: 32)),
      ElevatedButton(onPressed: () => setState(() => n++), child: const Text('+1')),
    ]),
  );
}

// ===== 3. ListView.builder =====
class Names extends StatelessWidget {
  final List<String> names;
  const Names({super.key, required this.names});
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: names.length,
      itemBuilder: (ctx, i) => ListTile(title: Text(names[i])),
    );
  }
}

// ===== 4. Navigator push =====
Navigator.of(context).push(MaterialPageRoute(builder: (_) => const DetailPage()));

// Or with go_router:
context.go('/detail/42');

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

Future<List<dynamic>> fetchUsers() async {
  final res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
  if (res.statusCode != 200) throw Exception('failed');
  return jsonDecode(res.body) as List;
}

// ===== 6. FutureBuilder =====
FutureBuilder<List<dynamic>>(
  future: fetchUsers(),
  builder: (ctx, snap) {
    if (snap.connectionState != ConnectionState.done) return const CircularProgressIndicator();
    if (snap.hasError) return Text('Error: ${snap.error}');
    final users = snap.data!;
    return ListView.builder(itemCount: users.length, itemBuilder: (c, i) => ListTile(title: Text(users[i]['name'])));
  },
);

// ===== 7. SharedPreferences persistence =====
import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveTheme(String theme) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('theme', theme);
}
Future<String> loadTheme() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString('theme') ?? 'light';
}

// ===== 8. Form with validation =====
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(children: [
    TextFormField(
      decoration: const InputDecoration(labelText: 'Email'),
      validator: (v) => (v?.contains('@') ?? false) ? null : 'invalid email',
    ),
    ElevatedButton(
      onPressed: () { if (_formKey.currentState!.validate()) { /* submit */ } },
      child: const Text('Sign in'),
    ),
  ]),
);

// ===== Patterns =====
// - ListView.builder for lazy lists
// - FutureBuilder for async data
// - Form + TextFormField for validation
// - SharedPreferences for small persistence
// - const constructors everywhere they fit

// ===== Pitfalls =====
// - Forgetting to dispose controllers
// - Calling setState after dispose -> error
// - Heavy build() methods -> extract widgets
// - Mixing async work directly in build (use FutureBuilder / state lib)

Why it matters

Eight small Flutter examples cover the daily 80%: layout, state, lists, navigation, http, FutureBuilder, persistence, forms. Pin them as a reference; the same patterns ship most app screens.

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

Example

Example
// Counters, lists, forms, navigation, theming, networking.
Try it Yourself »

Discussion

Loading…