nei*_*aro 5 concurrency dart dart-isolates flutter bloc
我正在尝试在 Flutter 应用程序中使用隔离和 Bloc 作为状态管理解决方案。现在,我在运行wallet_list.dart.
// wallet_list.dart
final FlutterSecureStorage _storage = const FlutterSecureStorage();
FutureOr<List<alan.Wallet>> getWalletList(int value) async {
Map<String, String> allValues = await _storage.readAll();
final List<alan.Wallet> _walletList = [];
allValues.forEach((key, value) {
if (key.startsWith(WalletOverviewHomeScreen.walletKey)) {
final arrMnemonic = value.split(' ');
final _wallet = alan.Wallet.derive(arrMnemonic, certikNetworkInfo);
// debugPrint('Adding wallet: $_wallet');
_walletList.add(_wallet);
}
});
Run Code Online (Sandbox Code Playgroud)
以下函数用于 cubit 类中的方法之一WalletInitializationCubit。
// inside WalletInitializationCubit
Future<void> getWalletListAndDefaultWallet() async {
try {
debugPrint('WalletListInitialization');
emit(WalletInitializationLoading());
final List<alan.Wallet> walletList = await compute(
getWalletList,
1
);
// other cubit logic
}
Run Code Online (Sandbox Code Playgroud)
尝试构建应用程序时,它返回以下错误:
Exception has occurred.
_AssertionError ('package:flutter/src/services/platform_channel.dart': Failed assertion:
line 134 pos 7: '_binaryMessenger != null || ServicesBinding.instance != null': Cannot use
this MethodChannel before the binary messenger has been initialized. This happens when you
invoke platform methods before the WidgetsFlutterBinding has been initialized. You can fix
this by either calling WidgetsFlutterBinding.ensureInitialized() before this or by passing
a custom BinaryMessenger instance to MethodChannel().)
Run Code Online (Sandbox Code Playgroud)
对于上下文,该main.dart文件看起来与此类似。
void main() async {
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
const MyApp();
@override
Widget build(BuildContext context) {
final ThemeData theme = ThemeData();
return MultiBlocProvider(
providers: [
BlocProvider<WalletInitializationCubit>(
create: (context) => WalletInitializationCubit(),
),
],
child: HomeScreen(),
.....
}
}
Run Code Online (Sandbox Code Playgroud)
导致错误的相关代码行是
// in getWalletList function
Map<String, String> allValues = await _storage.readAll();
Run Code Online (Sandbox Code Playgroud)
我尝试WidgetsFlutterBinding.ensureInitialized()在该行之前添加如下:
// in getWalletList function
WidgetsFlutterBinding.ensureInitialized()
Map<String, String> allValues = await _storage.readAll();
Run Code Online (Sandbox Code Playgroud)
但这会导致UI actions are only available on root isolate错误。
我该如何修复这个错误?我无法使用通常的使用方式async,await因为正在运行的进程相当繁重并导致应用程序冻结。
根据错误,UI actions are only available on root isolate很明显您无法WidgetsFlutterBinding.ensureInitialized()在隔离内部执行。另外,正如您在评论中提到的,_storage.readAll()方法会导致此问题。
考虑到这一点,您可以做的是在主隔离中运行_storage.readAll()(由主函数运行的内容)并将结果作为参数传递给隔离。
| 归档时间: |
|
| 查看次数: |
5897 次 |
| 最近记录: |