Building a Mobile dApp with Flutter

Intermediate

 

Building a Mobile dApp with Flutter

In this tutorial, you will learn how to build a mobile decentralized application (dApp) using Flutter, a popular open-source mobile application development framework. This tutorial will cover the tools and technologies needed to build mobile dApps, including Flutter, the Solidity programming language, Ganache and Truffle. We will also cover the key concepts of smart contract development, including contract deployment, testing, and interactions with a blockchain. This tutorial is aimed at developers and researchers interested in building decentralized mobile applications using Flutter and the Ethereum blockchain.

Setup Project

First of all, we need some tools installed, as said previously. Ganache can be installed following the instructions on their website ( ). It is useful to create contracts, deploy them, develop applications, and run tests. To install truffle, to begin, we will need node and npm installed. Once we have it installed, we can install truffle with the following command:

npm install -g truffle

To set up a project we will create a flutter project normally, and then we will initialize truffle within the project folder. This article is not a tutorial but an overview, but check my other articles to find tutorials on how to set up Flutter and start learning it.

flutter create projectname
cd projectname/
truffle init

Regarding folder structure, we will be using the following standard:

contracts/: Contains solidity files

migrations/: Migrations files to handle contract deployment with Truffle

test/: Test scripts

truffle-config.js: Truffle deployment configuration file

 

Writing contracts

The smart contracts will act as our backend/data/storage. We will create the Solidity files into our contracts/ folder as .sol.

 

Compiling contracts

In order to compile our Smart Contracts we will have to type in the terminal:

truffle compile

 

Migration

To configure migration, first, we will need to set up our truffle-config.js with the following content:

module.exports = {
  networks: {
     development: {
      host: "127.0.0.1",     // Localhost (default: none)
      port: 7545,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
     },
  },
    contracts_build_directory: "./src/artifacts/",
      
  // Configure your compilers
  compilers: {
    solc: {    
      
       // See the solidity docs for advice
       // about optimization and evmVersion
        optimizer: {
          enabled: false,
          runs: 200
        },
        evmVersion: "byzantium"
    }
  }
};

And then to execute the migration:

truffle migrate

Remember that you need to have Ganache running (Or you need to be connected to a Blockchain instead) in order to use truffle and execute the migration. If you’re using Ganache you will have your blockchain running at port 7545 as default.

Connecting with Flutter

Connecting with Flutter

A well-known library to connect a Flutter application to the Ethereum blockchain is web3dart. Between the features included we found:

  • Connect to an Ethereum node with the rpc-api, call common methods

  • Send signed Ethereum transactions

  • Generate private keys, setup new Ethereum addresses

  • Call functions on smart contracts and listen for contract events

In order to send transactions using web3dart we will need to set up some credentials. This can be done using a raw private key or v3 wallet files:

Using Private key example:

import 'dart:math'; //used for the random number generatorimport 'package:web3dart/web3dart.dart';
// You can create Credentials from private keys
Credentials fromHex = EthPrivateKey.fromHex("c87509a[...]dc0d3");// Or generate a new key randomly
var rng = new Random.secure();
Credentials random = EthPrivateKey.createRandom(random)(rng);// In either way, the library can derive the public key and the address
// from a private key:
var address = await credentials.extractAddress();
print(address.hex);

 

Using wallet file:

import 'dart:io';
import 'package:web3dart/web3dart.dart';String content = new File("wallet.json").readAsStringSync();
Wallet wallet = Wallet.fromJson(content, "testpassword");Credentials unlocked = wallet.privateKey;
// You can now use these credentials to sign transactions or messages

You can also create a Wallet file using a private key to encrypt and a desired password:

Wallet wallet = Wallet.createNew(credentials, "password", random);
print(wallet.toJson());

 

Sending transactions

Before sending transactions, we will have to connect to an RPC client (We can use a public API like infura, or setting up a private testnet with truffle and ganache). Having an endpoint to connect the library, we will be able to create, sign, and send Ethereum transactions.

If we’re using Ganache we can make use of its local RPC client, which you can get following the instructions of the picture:

Sending transactions

RPC Client — Ganache

Then you can get the private key directly from Ganache as well:

RPC Client — Ganache

Getting a private key from ganache

Here’s an example:

import 'package:http/http.dart'; //You can also import the browser version
import 'package:web3dart/web3dart.dart';var apiUrl = "http://localhost:7545"; //Replace with your APIvar httpClient = new Client();
var ethClient = new Web3Client(apiUrl, httpClient);var credentials = ethClient.credentialsFromPrivateKey("0x...");// You can now call rpc methods. This one will query the amount of Ether you own
EtherAmount balance = ethClient.getBalance(credentials.address);
print(balance.getValueInUnit(EtherUnit.ether));var credentials = ethClient.credentialsFromPrivateKey("0x...");await client.sendTransaction(
  credentials,
  Transaction(
    to: EthereumAddress.fromHex('0xC91...3706'),
    gasPrice: EtherAmount.inWei(BigInt.one),
    maxGas: 100000,
    value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1),
  ),
);

 

Conclusion

Decentralized apps are possible, and the tools are available. The API to use on mobile, at least with Flutter, gives the same possibilities as the web one for the public that uses this kind of apps in the phone. Depending on the quality/purpose of a web dApp, a mobile version should be native. The possibilities are huge, and combining the technology with Flutter to deliver iOS and Android apps using a single codebase will lead the way for a new age of decentralized apps that will fill our App stores.