Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature]: Asserting values are present when viewmodel.dataReady is true #1118

Open
TjardL opened this issue Aug 9, 2024 · 1 comment
Open
Labels
Feedback Requested Waiting for new information from the OP Improvement An issue to improve existing functionality

Comments

@TjardL
Copy link

TjardL commented Aug 9, 2024

Is your feature request related to a problem? Please describe.

When using a FutureViewModel, !viewModel.dataReady is a nice helper to indicate whether the data has been loaded. When it is true, one can be sure that the values are there. However, I still need to use ! on the viewModel.data in this case, despite being sure that the data is there. This is error prone because I might use the ! in instances where the data is indeed not there.

Describe the solution you would like

I image some kind of assertion when viewModel.dataReady is true such that when viewModel.data is used under this scope, the non-null return type can be used.
For now i have written the following extension function such that i can use viewModel.safeData, but i think it might be possible to use viewModel.data, and deduce the information that the data is loaded.

import 'package:stacked/stacked.dart';

extension SafeDataAccess<T> on DataStateHelper<T> {
  /// Asserts that data is non-null if dataReady is true and returns the data.
  T get safeData {
    if (!dataReady) {
      throw StateError('Data is not ready to be accessed');
    }
    return data as T; // Since dataReady is true, data is guaranteed to be non-null.
  }
}

Additional Context

image image
@FilledStacks
Copy link
Contributor

Interesting.

I also don't like the approach of nullable data, but it's the only way (we see currently) for future to operate successfully.

I like your safeData option.

You think you can make a PR with that change in the same place where the data property is currently located?

@FilledStacks FilledStacks added Feedback Requested Waiting for new information from the OP Improvement An issue to improve existing functionality labels Sep 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feedback Requested Waiting for new information from the OP Improvement An issue to improve existing functionality
Projects
None yet
Development

No branches or pull requests

2 participants