I try to connect a contract in web3 with flutter and run a method inside that. Our react-js developer give me these codes to connect to the getMoney
method:
const web3 = new Web3(Web3.givenProvider ||"https://rinkeby.infura.io/v3/...");
const contactList = new web3.eth.Contract(CONTACT_ABI, CONTACT_ADDRESS);
const getMoney = await contactList.methods.getMoney().call();
console.log(getMoney);
I try to use flutter_web3 package to connect to metamask and contract:
String abi = await rootBundle.loadString("assets/json/Counter.json");
final contract = Contract(CONTACT_ADDRESS, abi, Web3Provider("https://rinkeby.infura.io/v3/..."),);
int money = await contract.call("getMoney");
print(money.toString());
But I can't connect to contract and call getMoney
method. Can you help me?
CodePudding user response:
If I correctly understand, you want to call a method from the contract. I do that with web3dart and http package. Also, you need to do these jobs:
- First, you need an abi file. in your case, put your Counter.json file in the lib directory and rename that to
counter.abi.json
. - As web3dart#dart-code-generator said, You must add
build_runner
indev_dependency
and runpub run build_runner build
in the terminal. - Then, You'll now find a .g.dart file containing code to interact with the contract and you must use that class.
Then, initialize these codes:
Client httpClient = Client();
Web3Client ethClient = Web3Client("https://rinkeby.infura.io/v3/...", httpClient);
And for call a method from contract:
var contractAbi = await Counter(address: EthereumAddress.fromHex(contractAddress), client: ethClient);
var money = await contractAbi.getMoney();