How do I use a method defined in another code section in the same file?
import 'package:flutter/material.dart';
import 'package:flutter_web3/flutter_web3.dart';
class MetamaskProvider extends ChangeNotifier {
static const operationChain = 4;
String currentAddress = '';
int currentChain = -1;
bool get isEnabled => ethereum != null;
bool get isInOperatingChain => currentChain == operationChain;
bool get isConnected => isEnabled && currentAddress.isNotEmpty;
Future<void> connect() async {
if (isEnabled) {
final accs = await ethereum!.requestAccount();
if (accs.isNotEmpty) currentAddress = accs.first;
currentChain = await ethereum!.getChainId();
notifyListeners();
}
void clear() {
currentAddress = '';
currentChain = -1;
}
}
init() {
if (isEnabled) {
ethereum!.onAccountsChanged((accounts) {
clear();
});
ethereum!.onAccountsChanged((accounts) {
clear();
});
}
}
}
error thrown when trying to use the "clear" method: The method 'clear' isn't defined for the type 'MetamaskProvider'.
You have to move the method clear()
from connect()
method to outside of it. Then, you will be able to access clear()
inside init()
.
class MetamaskProvider extends ChangeNotifier {
static const operationChain = 4;
String currentAddress = '';
int currentChain = -1;
bool get isEnabled => ethereum != null;
bool get isInOperatingChain => currentChain == operationChain;
bool get isConnected => isEnabled && currentAddress.isNotEmpty;
void clear() {
currentAddress = '';
currentChain = -1;
}
Future<void> connect() async {
if (isEnabled) {
final accs = await ethereum!.requestAccount();
if (accs.isNotEmpty) currentAddress = accs.first;
currentChain = await ethereum!.getChainId();
notifyListeners();
}
}
init() {
if (isEnabled) {
ethereum!.onAccountsChanged((accounts) {
clear();
});
ethereum!.onAccountsChanged((accounts) {
clear();
});
}
}
}