I am trying to build a wallet app and implementing a key generation function. When I click the button, I want the function to generate a key. However, the screen freezes until the function finishes.
import 'package:flutter/material.dart';
import 'package:web3dart/crypto.dart';
import 'package:web3dart/web3dart.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:bip32/bip32.dart' as bip32;
class TestPage extends StatefulWidget {
const TestPage({super.key});
@override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
bool _isLoading = false;
@override
Widget build(BuildContext context) {
return _isLoading
? const Center(child: CircularProgressIndicator())
: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () async {
setState(() => _isLoading = true);
Credentials myCredentials = await _generateKeys();
print(myCredentials.address);
setState(() => _isLoading = false);
},
child: const Text('Generate credentials')),
),
);
}
_generateKeys() {
String mnemonic = generateMnemonic();
return generateKeysFromMnemonic(mnemonic);
}
Credentials generateKeysFromMnemonic(String mnemonic) {
final seed = bip39.mnemonicToSeed(mnemonic); // when this part runs, the screen freezes. T.T
final masterNode = bip32.BIP32.fromSeed(seed);
final bytesList = masterNode.privateKey;
final String privateKey = bytesToHex(bytesList!);
final Credentials credentials = EthPrivateKey.fromHex(privateKey);
return credentials;
}
String generateMnemonic() {
return bip39.generateMnemonic();
}
}
When I execute this function(generateKeysFromMnemonic), the screen freezes.
I tried using async/await, but it didn't work well...
Please help me. how can I prevent the screen from freezing?
I want the function to execute when the button is pressed, without freezing the screen until the result is returned.