selectChain method
Future<void>
selectChain(
- ReownAppKitModalNetworkInfo? chainInfo, {
- bool switchChain = false,
- bool logEvent = true,
override
Sets the selectedChain
If the wallet is already connected, it will request the chain to be changed and will update the session with the new chain.
If chainInfo
is null this will disconnect the wallet.
Implementation
@override
Future<void> selectChain(
ReownAppKitModalNetworkInfo? chainInfo, {
bool switchChain = false,
bool logEvent = true,
}) async {
_checkInitialized();
if (chainInfo?.chainId == _currentSelectedChainId) {
return;
}
// If the chain is null, disconnect and stop.
if (chainInfo == null) {
await disconnect();
return;
}
try {
_chainBalance = null;
final formattedBalance = CoreUtils.formatChainBalance(_chainBalance);
balanceNotifier.value = '$formattedBalance ${chainInfo.currency}';
final hasValidSession = _isConnected && _currentSession != null;
if (switchChain && hasValidSession && _currentSelectedChainId != null) {
final namespace = ReownAppKitModalNetworks.getNamespaceForChainId(
chainInfo.chainId,
);
final approvedChains = _currentSession!.getApprovedChains(
namespace: namespace,
);
final newCaip2Chain = ReownAppKitModalNetworks.getCaip2Chain(
chainInfo.chainId,
);
final hasChainAlready = (approvedChains ?? []).contains(newCaip2Chain);
if (!hasChainAlready) {
requestSwitchToChain(chainInfo);
final hasSwitchMethod = _currentSession!.hasSwitchMethod();
if (hasSwitchMethod) {
launchConnectedWallet();
}
} else {
await _setLocalEthChain(chainInfo.chainId, logEvent: logEvent);
}
} else {
await _setLocalEthChain(chainInfo.chainId, logEvent: logEvent);
}
} on JsonRpcError catch (e) {
onModalError.broadcast(ModalError(e.message ?? 'An error occurred'));
} on ReownAppKitModalException catch (e) {
onModalError.broadcast(ModalError(e.message));
} catch (e) {
onModalError.broadcast(ModalError('An error occurred'));
}
}