Cinnamon logo
Cinnamon logo
Cinnamon logo
Close

Home

Projects

Services

About Us

Careers

Blog

Contact Us

Close

Flutter, Cryptocurrency and Blockchain

Mihael Ivičić

2022-06-06

10min

Development

Recently, blockchain has gained popularity. This blog explains how can we use blockchain and smart contracts, and how decentralized apps are built.

placeholderFlutter_and_blockchain.png

Share this blog:

twitter logo
facebook logo
linkedin logo
link logo

Cryptocurrencies and blockchain have become increasingly popular in the last few years, so it is natural that we see a drive in the in the development of decentralized applications.

User adoption is still exceptionally low, but it is growing every day and the community keeps increasing.

The adoption of cryptocurrency and blockchain is much like the adoption of any other technology. The rate at which adoption occurs grows very gradually to a certain percent, then explodes upwards to mass adoption from there.

In this blog I will be explaining what blockchain and smart contracts are and how we can make use of them by providing an insight into how decentralized applications are developed.

What is blockchain?

Blockchain is an innovative technology that provides remarkably high security and decentralization using a distributed ledger. Everything that is on the blockchain is there to stay and can not be altered. The blockchain utilizes cryptography to assure that no one can alter the data on the blockchain. Every blockchain consists of blocks and validators. Blocks contain data, a cryptographic hash of previous blocks, and a timestamp to assure that the transaction data existed when the block was published and to get into its hash.

Because of this connection with every previous block by their hash, they form a chain. This means that if someone wants to alter the data of some block on the blockchain, they will need to alter all the previous blocks too, which is almost impossible (look up what a 51% Attack is). That is why blockchain is very secure by design.

Validators communicate with each other and are used to validate new blocks that come into the blockchain to assure that not a single altered block can get in.

Validators are a vital part of the blockchain because they are high powered computers that the blockchain operates on, without them, there would be no blockchain. But validators have one flaw. There is the potential risk of centralization. Although, when we talk about blockchain, we think of decentralization. That is because some blockchains, like Solana, a fast low-transaction fee blockchain, allow only people from the inner circle to operate a validator. This can lead to potential centralization of the blockchain, so we must pay attention to details like that.

The current problem that most new blockchains try to solve first is transaction speed, i.e. the amount of time that will pass for a new block to get validated. Secondly, they try to solve the high transaction fees that are present in some of the current blockchains. This is something Bitcoin and Ethereum have a problem with. Making a transaction on Ethereum can cost you anything, ranging from $4 to as much as $70 or more.

The workaround is to use wrapped assets on other faster blockchains that have lower transaction fees to move those assets. A wrapped asset is an asset that exists on the blockchain that is not native to itself but is the same as the one on the native blockchain. This way, we can send wrapped Ethereum on some other lower transaction fee blockchain, for example, Solana’s fees are measured in cents. That way, you can send Ethereum or Bitcoin for a much lower price than if you would have sent it on their native blockchain.

Smart Contracts

A smart contract is a piece of code that, simply put, is a set of methods and states that execute automatically when predetermined conditions are met following a certain protocol or when a user calls them.

I like to perceive them as an API which is hosted on the blockchain. You have certain data and a set of methods that do something with that data, similar to centralized APIs, but in this case, we do not have a database.

Most people describe them as vending machines. They are no smarter than you make them and they have fixed predetermined conditions.

When you insert money into a vending machine and select your item, it will give you an item and your change, but if you do not have enough money, the vending machine will not give you an item.

Everything is executed automatically once the user inserts money and selects the item. Smart contracts work the same way.

They are stored and executed on the blockchain, so we can be sure that no one can change the written methods inside that contract to gain personal benefit unless you have a bug in your code.

Because of smart contract’s ability to self-execute automatically when certain rules are met, there is no need for third parties to stand in between. For example, we can make a platform for fundraising that will release the money to a predetermined address of an organizer when it reaches a certain goal.

Collecting the funds and sending the money to the organizer is done completely by a smart contract without the need for a third-party company to interfere with the money and take its cut.

The second idea would be a decentralized uber application. A dapp that connects the nearest drivers and passengers. The only additional cost besides the cost of the drive would be gas fees (cost per transaction on the blockchain).

The taxi driver gets the full amount of what the user paid. There would still be a need for a company to review those taxi driver applications, but it would still be much more profitable to drivers and consumers.

Because of decentralization and the security blockchain provides, smart contracts and blockchain have a lot of potential use cases that we will see in the future. It has the potential to change the world for the better.

Smart contracts for Ethereum are written in a language called Solidity which was created and developed by Ethereum founder Vitalik Buterin.

It is interesting that the term smart contract was first used by Nick Szabo in 1994. He stated that, “A smart contract is a computerized transaction protocol that executes the terms of a contract.”

Developing a Flutter Dapp on the Ethereum blockchain

Dapp stands for "decentralized application". These are applications that communicate with the blockchain by using smart contracts. This type of development involves creating applications that send transactions with instructions to on-chain smart contracts and very closely resembles building web/mobile apps and interacting with centralized APIs. We are going to write a simple smart contract and develop a simple Flutter Dapp that interacts with our smart contract.

1. Setup

Firstly, we need to set up our environment in which we will test and deploy the contract. Truffle is the most popular development framework for Ethereum. We need to install Ganache which is used to quickly fire up a personal Ethereum blockchain which you can use to run tests, execute commands, and inspect states while controlling how the chain operates. For this to work you will also need to have Node.js installed on your computer. When you are done installing Node.js you need to execute the following command in the terminal.

npm install -g truffle

Secondly, we must create a new Flutter project with a specific directory structure as shown in picture 1. This is done by running the below command in the terminal inside our project root directory and everything gets automatically generated for us. You can find the terminal inside Android Studio close to the bottom.

truffle init

Picture 1 - Project directory structure

  • contracts/: solidity contract files

  • migrations/: migration script files that are used by Truffle

  • test/: test script files.

  • truffle-config.js: truffle deployment configuration

2. Writing the smart contract

The next step is to write the smart contract itself. This will be done through Android Studio. There is also a special IDE for Solidity called Remix but since we are testing a smart contract on the Ganache personal blockchain and we are developing a Flutter application, we will write our contract inside a contracts folder in our Flutter project from which it is going to be compiled and deployed.

For this application we will keep things simple and only write a basic smart contract and Flutter application with a minimalistic UI. I recommend installing the Solidity plugin for Android Studio. This is done by going to Preferences -> Plugins

When you are done installing the plugin, right click on the contracts directory and click New Solidity file. Name it SimpleStorage.

Add the following content to the file:

Picture 2 - Simple smart contract

This smart contract allows anyone to store a certain number on the Ethereum blockchain which can be seen or overwritten by anyone that calls our smart contract. Notice how we defined our functions as public. Public functions can be called outside of smart contracts by users or other smart contracts.

3. Compiling

To compile our smart contract, we must run the following command in our terminal. If you have a problem compiling, try to use the terminal with administrator privileges.

truffle compile

4.Migration

The next thing we need to do is migrate our smart contract to the blockchain. In the root of project right click on the migrations folder and create a new file named 2_deploy_contracts.js.

Add the following content to the file:

Picture 3 - Migration file

To proceed further with migration, we need to have our blockchain running. We use Ganache for that. Just double click on the icon and launch the app then click on QuickStart. This will generate a blockchain running locally on port 7545.

Picture 4 - Ganache personal blockchain

The next step is to change the truffle-config.js file. Paste in the following code:

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: {    
      version:"0.8.13",
       // See the solidity docs for advice
       // about optimization and evmVersion
        optimizer: {
          enabled: false,
          runs: 200
        },
        evmVersion: "byzantium"
    }
  }
};

We are all set to deploy our smart contract on the Ethereum blockchain. Run the following command in the terminal:

truffle migrate

Deployment costs 0.007 ETH in gas fees as you can see on Picture 5. Our contract is now deployed on our test blockchain.

Picture 5 – Transaction history

5. Link the contract with Flutter

To link the contract with Flutter we need to add a few packages to our project. Add the following to pubspec.yaml file:

get: ^4.6.1
web3dart: ^2.3.5
http: ^0.13.4
web_socket_channel: ^2.1.0

You also need to add this under the assets in pubspec.yaml:

assets:
    - src/artifacts/SimpleStorage.json

The next step is to make a dart file for constants, name it constants, and paste the following:

class BlockchainConstants {
  static const String rpcUrl = "http://10.0.2.2:7545";
  static const String wsUrl = "ws://10.0.2.2:7545/";
  static const String privateKey =
      "4d7040ace46a9367e6d9c87d87a22de32ad443facd326bb41c30ce5a0b12f5ea";
}

Replace _privateKey with your own. Find it by clicking on the key icon of the first account on the home screen of Ganache

Picture 6 – Private key

6. UI with controller & contract service

For this part you will have to go to my GIT repository and copy paste the remaining part of the application. There is too much code to cover here. For state management I have used GetX which you can find out more about on the other blog post here.

When you enter the number and click on the blue button you will see the change of the current number immediately. You can also check the history of calls made to smart contracts in Ganache as seen in Picture 8.

Picture 7 – Flutter app

Check out the full GIT repository here. If you clone this repo, be sure to turn on Ganache and change the _privateKey to yours in the constants.dart file for the Flutter app to work. Also do not forget to run command for contract migration. Thanks for reading!

Share this blog:

twitter logo
facebook logo
linkedin logo
link logo

Subscribe to our newsletter

We send bi-weekly blogs on design, technology and business topics.

Similar blogs

placeholderLate_initializers.png

Development

Josip Kilić

2022-06-06

5min

Null safety and late initializers in Flutter
placeholderFlutter_course_done.png

Marketing

Marketing

2022-05-20

5min

Cinnamon College: Flutter Course
placeholderStateMagementInFlutter.jpg

Development

Josip K.

2021-02-11

7min

State Management in Flutter
Job application illustration

You could use our expertise?

Let's work together.