Skip to content

Instantly share code, notes, and snippets.

@henry2man
Last active April 26, 2022 07:21
Show Gist options
  • Save henry2man/f5e8e15b180f88486ca35e24870286f0 to your computer and use it in GitHub Desktop.
Save henry2man/f5e8e15b180f88486ca35e24870286f0 to your computer and use it in GitHub Desktop.
ValueHolder - Dart / Flutter utility class to use with state management packages. It is used to model the loading of information in the background. In the example it is used with BloC, but it can be used with any other state management library.
Widget namesWidget() {
return BlocBuilder<ExampleBloc, ExampleState>(
buildWhen: (previous, current) =>
previous.names != current.names,
builder: (context, state) {
if(state.names.loading) {
return Text("Loading names...");
} else if (state.names.error != null) {
return Text("Error: ${state.names.error}", style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold));
} else {
return Text("Names are: ${state.names.value.join(",")}");
}
});
}
class ExampleBloc
extends Bloc<ExampleEvent, ExampleState> {
const ExampleBloc ({}) {
on<InitState>(_onInitState);
}
FutureOr<void> _onInitState(event, emit) async {
emit(ExampleState());
emit(this.state.copyWith(
names: ValueHolder(value: null, loading: true),
));
// TODO Fetch async data from a repository/API...
Future.delayed(Duration(milliseconds: 1000), ()=>["John", "Jane", "Juan", "Joan",])
.then((names) => emit(this.state.copyWith(
names: names, loading: false,
)))
.onError((error, stackTrace) {
emit(this.state.copyWith(
names: ValueHolder(value: null, loading: false, error: "$error")
));
});
}
}
class ExampleState extends Equatable {
const ExampleState({
this.names = const ValueHolder(value: null),
});
final ValueHolder<List<String>?> names;
final copyWith({
ValueHolder<List<String>?>? names,
}) {
return ExampleState(
names: names ?? this.names,
);
}
@override
List<Object> get props => [
names,
];
}
abstract class ExampleEvent extends Equatable {
const ExampleEvent();
@override
List<Object?> get props => [];
}
class InitState extends ExampleEvent {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment