Skip to content

Instantly share code, notes, and snippets.

@ampersanda
Last active August 14, 2020 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ampersanda/fdb74814101b69a48f7a524241a0acd2 to your computer and use it in GitHub Desktop.
Save ampersanda/fdb74814101b69a48f7a524241a0acd2 to your computer and use it in GitHub Desktop.
Mixin Collections
import 'dart:async';
import 'package:flutter/widgets.dart';
/// provide single [TextField] debounce timer and handle controller and callback
/// by implementing [SingleFieldDebounceState] in [State] class
///
mixin SingleFieldDebounceProvider<T extends StatefulWidget>
on SingleFieldDebounceState<T> {
Timer _debouncedSearchTimer;
final TextEditingController debouncedController = TextEditingController();
@override
void dispose() {
super.dispose();
debouncedController.dispose();
_debouncedSearchTimer?.cancel();
}
/// can be used to fill [TextField.onChanged] event
///
void onDebounceFieldChange(String value) {
if (_debouncedSearchTimer != null) {
_debouncedSearchTimer.cancel();
}
_debouncedSearchTimer = Timer(_debounceDuration, () {
onDebounceDone(value);
});
}
}
abstract class SingleFieldDebounceState<T extends StatefulWidget>
extends State<T> {
void onDebounceDone(String value);
Duration get _debounceDuration => const Duration(milliseconds: 700);
}
import 'dart:async';
/// This mixin can help you
mixin StoreCompleterMixin {
/// completer is used because of getting from storage is asynchronous
final Completer<bool> storeCompleter = Completer<bool>();
/// [completed] can be used to check whether data is ready
Future<bool> completed({
Duration timeoutDuration = const Duration(seconds: 5),
}) async {
try {
final bool completed = await storeCompleter.future
.timeout(timeoutDuration)
.catchError(() => false);
return completed && storeCompleter.isCompleted;
} catch (e) {
return false;
}
}
void maySetComplete() {
if (!storeCompleter.isCompleted) {
storeCompleter.complete(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment