Improve init. Close #236

This commit is contained in:
2025-03-04 15:30:40 +08:00
parent 0f6874f8d7
commit 7b5c13200d
14 changed files with 184 additions and 105 deletions

40
lib/utils/init.dart Normal file
View File

@@ -0,0 +1,40 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
/// A mixin class that provides a way to ensure the class is initialized.
abstract mixin class Init {
bool _isInit = false;
final _initCompleter = <Completer<void>>[];
/// Ensure the class is initialized.
Future<void> ensureInit() async {
if (_isInit) {
return;
}
var completer = Completer<void>();
_initCompleter.add(completer);
return completer.future;
}
Future<void> _markInit() async {
_isInit = true;
for (var completer in _initCompleter) {
completer.complete();
}
_initCompleter.clear();
}
@protected
Future<void> doInit();
/// Initialize the class.
Future<void> init() async {
if (_isInit) {
return;
}
await doInit();
await _markInit();
}
}