Last active
August 14, 2020 10:32
-
-
Save ampersanda/fdb74814101b69a48f7a524241a0acd2 to your computer and use it in GitHub Desktop.
Mixin Collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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