Flutter中Supabase v1.0版本无需.execute()如何获取数据及单个值?
Great question! The v1.0 update to supabase-flutter simplified query syntax by removing the need for .execute(), but it takes a minute to adjust to retrieving actual data now. Let’s break this down:
1. Fetching the Full Dataset
In v1.0+, the select() method returns a Future directly, so you just need to await it to get your data (no more .execute()). The result will be a List<Map<String, dynamic>> which you can use immediately:
try { // Await the query to get the actual data list final List<Map<String, dynamic>> data = await supabase.from('my_table').select(); // Use the data however you need—loop through it, access specific entries, etc. for (final item in data) { print('Item ID: ${item['id']}, Name: ${item['name']}'); } } catch (error) { // Handle errors properly—most will be PostgrestError type if (error is PostgrestError) { print('Query failed: ${error.message} (Code: ${error.code})'); } else { print('Unexpected error: $error'); } }
2. Getting a Single Value or Record
If you need a single record or a specific field value, you can use methods like single(), maybeSingle(), or target specific fields in your select():
Case 1: Get a Single Record
Use single() when you expect exactly one result (it throws an error if no records match or multiple do):
try { // Fetch the record where id = 1 final Map<String, dynamic> singleRecord = await supabase .from('my_table') .select() .eq('id', 1) .single(); // Extract a specific value from the record final String userEmail = singleRecord['email'] as String; print('User Email: $userEmail'); } catch (error) { if (error is PostgrestError) { print('Failed to fetch record: ${error.message}'); } }
Case 2: Get a Single Value Safely
Use maybeSingle() if you want to avoid errors when no record is found (it returns null instead):
try { // Fetch only the 'username' field for id = 1 final Map<String, dynamic>? record = await supabase .from('my_table') .select('username') .eq('id', 1) .maybeSingle(); // Extract the single value (handle null case) final String? username = record?['username'] as String?; if (username != null) { print('Username: $username'); } else { print('No user found with that ID'); } } catch (error) { print('Error: $error'); }
Case 3: Get Aggregate Values (like counts)
For values like total records, use select() with head and count parameters:
try { // Get the exact count of records in my_table final int totalRecords = await supabase .from('my_table') .select('count', head: true, count: CountOption.exact) as int; print('Total records: $totalRecords'); } catch (error) { print('Failed to get count: $error'); }
Key Takeaways
- Always await your
select()(and other query methods) since they return Futures now single()enforces exactly one result;maybeSingle()is safer for optional records- Extract values directly from the returned
Mapor cast aggregate results to your desired type
内容的提问来源于stack exchange,提问作者Raka M.A

