Writing the Smart Contract
The Smart Contract actually acts as the back-end logic and storage for our Dapp.
- Create a new file named Population.sol in the contracts/ directory.
- Add the following content to the file:
Solidity
pragma solidity ^0.5.0; contract Population { } |
- The minimum version of Solidity required is noted at the top of the contract: pragma solidity ^0.5.9;.
- Statements are terminated with semicolons.
Variable setup
- Add the following variable on the next line after contract Population {
Solidity
string public countryName ; uint public currentPopulation ; |
- countryName and currentPopulation will hold the name and population of the country.
- It is defined as public modifier because solidity automatically creates getter functions for all public state variables.
Constructor
Solidity
constructor() public { countryName = "Unknown" ; currentPopulation = 0 ; } |
Constructor in solidity is executed only once, when a contract is created and it is used to initialize contract state. Here we’re just setting the initial value of the variables.
Function
- Add the following function to the smart contract after the constructor declaration we set up above.
Solidity
function set(string memory name, uint popCount) public { countryName = name ; currentPopulation = popCount ; } function decrement(uint decrementBy) public { currentPopulation -= decrementBy ; } function increment(uint incrementBy) public { currentPopulation += incrementBy ; } |
- set function is used to set the countryName and currentPopulation as specified by the user.
- decrement function will decrement the currentPopulation with the specified count.
- increment function will increment the currentPopulation with the specified count.
Flutter and Blockchain – Population Dapp
Before checking out this article, Do take a look at Flutter and Blockchain – Hello World Dapp. This tutorial will take you through the process of building your mobile dapp – Population on Blockchain!
This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of the Flutter framework but are new to mobile dapps.
In this tutorial we will be covering:
- Setting up the development environment
- Creating a Truffle Project
- Writing the Smart Contract
- Compiling and Migrating the Smart Contract
- Testing the Smart Contract
- Contract linking with Flutter
- Creating a UI to interact with the smart contract
- Interacting with the complete Dapp
Description
Population on blockchain is a simple decentralized application, which will allow you to store a specific country population on the blockchain, you can increment as well as decrement the population based on the current condition of the country.
Output: