Supabase in Flutter: solved exercise with auth and task CRUD

Supabase in Flutter: solved exercise with auth and CRUD

Supabase is the most widely used open-source Firebase alternative in 2025-26. It combines a PostgreSQL database, authentication, storage, and edge functions in a single service. supabase_flutter provides an official client that handles sessions, tokens, and API communication reactively.

Problem statement

Build a task manager app that:

  • Allows registration and sign-in with email and password.
  • Shows the tasks screen only when a session is active.
  • Creates, completes, and deletes tasks in Supabase.
  • Applies Row Level Security so each user only sees their own tasks.
  • Handles authentication errors with readable messages.

Dependencies

1
2
3
4
dependencies:
  flutter:
    sdk: flutter
  supabase_flutter: ^2.8.0

Configuration

1. Create a Supabase project (supabase.com) and copy the URL and anon key from Settings → API.

2. Create the tasks table in the Supabase SQL Editor:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
create table tasks (
  id         uuid primary key default gen_random_uuid(),
  user_id    uuid references auth.users not null,
  title      text not null,
  done       boolean not null default false,
  created_at timestamptz default now()
);

-- Enable Row Level Security
alter table tasks enable row level security;

-- Policy: each user accesses only their own tasks
create policy "crud_own_tasks"
  on tasks
  for all
  using  (auth.uid() = user_id)
  with check (auth.uid() = user_id);

3. Initialize Supabase before runApp:

1
2
3
4
await Supabase.initialize(
  url: 'https://YOUR_PROJECT.supabase.co',
  anonKey: 'your_anon_key',
);

In production, store credentials with --dart-define or environment variables, never in source code.

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

// ── Entry point ───────────────────────────────────────────────────────────────
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Supabase.initialize(
    url: const String.fromEnvironment('SUPABASE_URL'),
    anonKey: const String.fromEnvironment('SUPABASE_ANON_KEY'),
  );
  runApp(const MyApp());
}

// Global client access (official supabase_flutter pattern)
final supabase = Supabase.instance.client;

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Supabase Tasks',
      theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.teal),
      home: const AuthGate(),
    );
  }
}

// ── AuthGate: shows Login or Tasks based on session state ─────────────────────
class AuthGate extends StatelessWidget {
  const AuthGate({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AuthState>(
      stream: supabase.auth.onAuthStateChange,
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }
        final session = snapshot.data!.session;
        return session != null ? const TasksPage() : const LoginPage();
      },
    );
  }
}

// ── Model ─────────────────────────────────────────────────────────────────────
class Task {
  final String id;
  final String title;
  final bool done;

  const Task({required this.id, required this.title, required this.done});

  factory Task.fromJson(Map<String, dynamic> json) => Task(
        id: json['id'] as String,
        title: json['title'] as String,
        done: json['done'] as bool,
      );
}

// ── LoginPage ─────────────────────────────────────────────────────────────────
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _emailCtrl = TextEditingController();
  final _passCtrl = TextEditingController();
  bool _loading = false;

  Future<void> _signIn() async {
    setState(() => _loading = true);
    try {
      await supabase.auth.signInWithPassword(
        email: _emailCtrl.text.trim(),
        password: _passCtrl.text,
      );
    } on AuthException catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text(e.message)));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _signUp() async {
    setState(() => _loading = true);
    try {
      await supabase.auth.signUp(
        email: _emailCtrl.text.trim(),
        password: _passCtrl.text,
      );
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Check your email to confirm registration')),
        );
      }
    } on AuthException catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text(e.message)));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  void dispose() {
    _emailCtrl.dispose();
    _passCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Sign in to Supabase Tasks')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _emailCtrl,
              decoration: const InputDecoration(labelText: 'Email'),
              keyboardType: TextInputType.emailAddress,
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _passCtrl,
              decoration: const InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            const SizedBox(height: 24),
            if (_loading)
              const CircularProgressIndicator()
            else
              Row(
                children: [
                  Expanded(
                    child: FilledButton(
                      onPressed: _signIn,
                      child: const Text('Sign in'),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: OutlinedButton(
                      onPressed: _signUp,
                      child: const Text('Register'),
                    ),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

// ── TasksPage ─────────────────────────────────────────────────────────────────
class TasksPage extends StatefulWidget {
  const TasksPage({super.key});

  @override
  State<TasksPage> createState() => _TasksPageState();
}

class _TasksPageState extends State<TasksPage> {
  List<Task> _tasks = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadTasks();
  }

  Future<void> _loadTasks() async {
    setState(() => _loading = true);
    final data = await supabase
        .from('tasks')
        .select()
        .order('created_at', ascending: false);
    if (mounted) {
      setState(() {
        _tasks = (data as List).map((e) => Task.fromJson(e)).toList();
        _loading = false;
      });
    }
  }

  Future<void> _addTask(String title) async {
    await supabase.from('tasks').insert({
      'title': title,
      'done': false,
      'user_id': supabase.auth.currentUser!.id,
    });
    await _loadTasks();
  }

  Future<void> _toggleTask(Task task) async {
    await supabase
        .from('tasks')
        .update({'done': !task.done})
        .eq('id', task.id);
    await _loadTasks();
  }

  Future<void> _deleteTask(String id) async {
    await supabase.from('tasks').delete().eq('id', id);
    await _loadTasks();
  }

  void _showAddDialog() {
    final ctrl = TextEditingController();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('New task'),
        content: TextField(
          controller: ctrl,
          autofocus: true,
          decoration: const InputDecoration(hintText: 'Description'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('Cancel'),
          ),
          FilledButton(
            onPressed: () async {
              Navigator.pop(ctx);
              if (ctrl.text.trim().isNotEmpty) {
                await _addTask(ctrl.text.trim());
              }
            },
            child: const Text('Add'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My tasks'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            tooltip: 'Sign out',
            onPressed: () => supabase.auth.signOut(),
          ),
        ],
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _tasks.isEmpty
              ? const Center(child: Text('No tasks yet. Tap + to add one.'))
              : ListView.builder(
                  itemCount: _tasks.length,
                  itemBuilder: (context, index) {
                    final task = _tasks[index];
                    return ListTile(
                      leading: Checkbox(
                        value: task.done,
                        onChanged: (_) => _toggleTask(task),
                      ),
                      title: Text(
                        task.title,
                        style: task.done
                            ? const TextStyle(
                                decoration: TextDecoration.lineThrough)
                            : null,
                      ),
                      trailing: IconButton(
                        icon: const Icon(Icons.delete_outline),
                        onPressed: () => _deleteTask(task.id),
                      ),
                    );
                  },
                ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddDialog,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Key concepts

APIPurpose
Supabase.initialize()Initializes the global client once at startup
supabase.auth.onAuthStateChangeReactive stream of session state
supabase.auth.signInWithPassword()Sign in with email and password
supabase.auth.signUp()Register a new user
supabase.auth.signOut()Close the active session
supabase.from('table').select()Read records (RLS enforced automatically)
supabase.from('table').insert({})Create a record
supabase.from('table').update({}).eq()Update by condition
supabase.from('table').delete().eq()Delete by condition
AuthExceptionTyped auth error with a readable message

Common mistakes

  • Credentials in source code: use --dart-define or a secrets manager. The Supabase anon key is not an absolute secret (protected by RLS), but the URL should still be controlled in production.
  • Missing await on write operations: insert, update, and delete are Future; without await you won’t see errors and state won’t update.
  • RLS enabled without policies: if you enable RLS without creating policies, all queries return 0 records even if data exists — correct by design, but confusing when undocumented.
  • Not checking mounted after await: the widget may have been disposed during the async operation; always check mounted before calling setState or ScaffoldMessenger.

Practical application

This pattern is the foundation for any app with users and private data: note managers, lightweight CRMs, personal tracking apps, or internal admin dashboards. Supabase adds real-time subscriptions via supabase.from('tasks').stream() when you need instant updates without polling.

Guided practice and next step

FAQ

Is Supabase free for small projects?

Yes. The free plan includes 500 MB of database storage, 50,000 monthly active users, and 2 GB of file storage. It is enough for MVPs and personal projects.

What is the main difference from Firebase?

Firebase uses a NoSQL database (Firestore) while Supabase uses relational PostgreSQL. Supabase is open-source and can be self-hosted; Firebase is a Google service with no self-hosting option.

How do I protect the anon key in production?

The anon key is not a critical secret because data access is controlled by Row Level Security. What you must never expose is the service_role key, which bypasses RLS entirely and must never be used on the client side.