How do you automatically set a UUID for a row in Supabase using the Flutter SDK?

544 views Asked by At

I see in the Supabase docs that there is a built-in gen_random_uuid() function which can be used to generate an ID automatically for each new row. For some reason this isn't working for me. When I try to create a new user I get this error:

PostgrestException(message: null value in column "id" of relation "users" violates not-null constraint, code: 23502, details: Bad Request, hint: null)

Here is my table schema:

enter image description here

And here is my ID column setup:

enter image description here

On the Flutter side, I am creating a new user like this:

Future<void> createUser() async {
    try {
      FastUser newUser = FastUser(createdAt: DateTime.now());

      await _supabase.from('users').insert(newUser.toJson());
    } catch (e) {
      debugPrint('Error creating user: $e');
      rethrow;
    }
  }
1

There are 1 answers

0
Yes Dev On

I found the issue. I was using the @JsonSerializable annotation which includes all null values by default in the toJson() output.

To fix this, I needed to add @JsonKey(includeIfNull: false) over the "id" field:

import 'package:json_annotation/json_annotation.dart';
import 'package:neurd/features/shared/utils/json/utils.dart';

part 'fast_user.g.dart';

@JsonSerializable(explicitToJson: true)
class FastUser {

  @JsonKey(includeIfNull: false) // Added this
  String? id;

  String? email;

  FastUser({
    this.id,
    this.email,
  });

  factory FastUser.fromJson(Map<String, dynamic> json) => _$FastUserFromJson(json);

  Map<String, dynamic> toJson() => _$FastUserToJson(this);
}