1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Discrimination type Unions in Dart with freezed, with overloading constructors or...

Discussão em 'Mobile' iniciado por Stack, Outubro 25, 2024 às 12:23.

  1. Stack

    Stack Membro Participativo

    I would like to know if there is any good approach to the following problem in Flutter / Dart.

    I would like to define a Result type as a discriminated union using the freezed package.

    I'll present in a bit what I have currently, but first the desired features:

    • Must be discriminated union, such that Success and Error are completely distinguished between these two 'main' options.
    • Have more specific or restricted 'overload' types of the Success types, so that these can be narrowed down further and handled differently. (Some methods just need to continue the flow, whereas others might need to display a Success dialog)
    • At least one success type should support a generic constructor, such that a return value of any type can be handled if some operation was successful before.

    I'll show you what I mean. I have the following code.

    @freezed
    sealed class Result<T> with _$Result<T> {
    const Result._();

    // default success constructor with no value and no message, and is used only
    // to indicate a successful operation
    const factory Result.success() = Success;

    // success constructor with a generic value resulting from the operation
    const factory Result.successValue(T value) = SuccessValue<T>;

    // success constructor with an explicit message and an optional generic value
    // can be used in UI elements like Dialogs, Snackbars, etc.
    const factory Result.successMessage(String message, [T? value]) =
    SuccessMessage<T>;

    // error constructor with an optional message
    const factory Result.error([String? message]) = Error;

    bool get isSuccess =>
    this is Success || this is SuccessMessage || this is SuccessValue;
    }


    I feel like I'm lacking a piece of 'type safety' when it comes to Success comparisons. What I would actually want, is that all the constructor types 'Success | SuccessValue | SuccessMessage ' are all related and recognized as a general 'Success' type. Either they should be overloads of the same type, or somehow inheritance between a parent 'Success' type, and more restricted children types 'SuccessValue and SuccessMessage' should be defined.

    This is the reason that I expose an isSuccess getter, but the mistake can still be made by a developer that the erroneous comparison "result is Success" can be made.

    Continue reading...

Compartilhe esta Página