How to connect contract in web3 with flutter

343

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:

  1. 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.
  2. As web3dart#dart-code-generator said, You must add build_runner in dev_dependency and run pub run build_runner build in the terminal.
  3. 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();
Share:
343
Marlen Schreiner
Author by

Marlen Schreiner

Updated on January 03, 2023

Comments

  • Marlen Schreiner
    Marlen Schreiner over 1 year

    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?