Build Cryptocurrency App From Scratch

in #utopian-io7 years ago

Github Repository:

What Will I Learn?

  • You learn how to build layouts
  • You learn using and creating widgets
  • You learn widget decoration
  • You learn basic dart
  • You learn how to create cryptocurrency app

Requirements

System Requirements:

  • IDEA intellij, Visual Studio Code with the Dart/Flutter Plugins, Android Studio or Xcode
  • The Flutter SDK on the latest Master Build
  • An Android or iOS Emulator or device for testing

OS Support for Flutter:

  • Windows 7 SP1 or later (64-bit)
  • mac OS (64-bit)
  • Linux (64-bit)

Required Knowledge

  • A little understanding of key/value stores
  • A fair understanding of Mobile development and Imperative or Object Oriented Programming
  • Some understanding of real time databases

Resources for Flutter and this Project:

Difficulty

  • Basic

All Code:

Getting Started

On Android Studio or IntelliJ, tap on the File menu - > New - > New Flutter Project. In the event that you don't see the New Flutter Project alternative, guarantee you have introduced the Flutter plugin. In the event that you are utilizing Visual Studio Code, take after the means here to make another project.

At the point when the page opens, select Flutter Application and tap on the Next.

The following page gives you a chance to arrange the task. You can utilize a comparative design like the picture underneath. Simply guarantee that the Flutter SDK way indicates the registry where you downloaded Flutter.

The last page gives you a chance to design your organization area name, and you can set it to any space name. From that point onward, tap on the Finish.

The project creation should start subsequent to tapping the complete, which for the most part takes a couple of minutes.
At the point when it's set, your undertaking should resemble this.

A file called main.dart was made in the lib organizer. It contains code for a demo application. Since we will manufacture our application starting with no outside help, open up the main.dart record and erase/clear all the code in it.
In the event that your task incorporates a test catalog that contains the document widget_test.dart, erase this record before proceeding. It contains tests for the code we just erased.

Flutter applications are written in the Dart programming language. The main.dart file is a Dart source record (.dart extension). The Dart tradition is to name source records utilizing lowercase_with_underscores.
How about we begin keeping in touch with some Dart code. We will start with the programming custom: printing "Hello World!"

To do that we should make something many refer to as the main function. The principle work is a best level capacity that each Flutter application has that fills in as the section point into your application. Consider it like the passageway to a house.

When you run your application on a gadget, execution will begin from the fundamental capacity. We should make a straightforward primary capacity, so enter the accompanying code into your main.dart document.

void main() async {

  Injector.configure(Flavor.PROD);

  runApp(new MyApp());

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      theme: new ThemeData(

          primarySwatch: Colors.pink,

          primaryColor: defaultTargetPlatform == TargetPlatform.iOS

              ? Colors.grey[100]

              : null),

      home: new HomePage(),

    );

  }

}

github : https://github.com/iampawan/CryptoApp/blob/master/lib/main.dart

As should be obvious, making the main function is simple. The second line contains the main function affirmation: its arrival type(void) and name (main). The main function returns void importance it returns nothing.

The third line does the printing to the support. We call the print capacity and pass a string contention to it. Note that in Dart, you can utilize single statements ('string') or twofold statements ("string") while announcing a string strict.

To run the code, tap on the green run (play) catch at the highest point of Android Studio or IntelliJ. Guarantee you have a genuine gadget associated or you have an emulator running.

However, in the event that you check your gadget or emulator, you will see something baffling.

A blank screen

All things considered, this was normal, as we are at present just printing to the support. There was nothing added to the application UI, and that is the reason it is clear.

So how about we settle this by adding a few components to the application UI. Our application will utilize material outline, so how about we add a bundle to the main.dart document to help with that.

     import'package:flutter/material.dart';

code source : https://github.com/iampawan/CryptoApp/blob/master/lib/main.dart

Much the same as any cutting edge programming dialect, you can import a library/bundle to use in your code. Here we are bringing in the material.dart bundle. This bundle contains code that causes us make a material styled application.

The material.dart bundle has a capacity called runApp. The runApp takes a widget and joins it to the screen. All things considered,
what is a widget?

widget

You can consider widgets perspectives or UI components. They are the things you see (and some you don't see) when you run your application on a widget. In Flutter, you will utilize widgets a great deal, on the grounds that the fundamental thought is that your application UI is made altogether out of widgets.

Vacillate as of now accompanies a suite of capable gadgets like content and pictures. The material.dart bundle we simply foreign made has a few material outline widgets that we will utilize in no time.

How about we utilize the runApp technique currently to indicate "Hi World!" at the focal point of the widget screen. Supplant the substance of the main function with the code underneath.

void main() async {

  Injector.configure(Flavor.PROD);

  runApp(new MyApp());

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      theme: new ThemeData(

          primarySwatch: Colors.pink,

          primaryColor: defaultTargetPlatform == TargetPlatform.iOS

              ? Colors.grey[100]

              : null),

      home: new HomePage(),

    );

  }

}

code source : https://github.com/iampawan/CryptoApp/blob/master/lib/main.dart

Give me a chance to clarify a portion of the new stuff in the code above

  • new: To make a protest, you for the most part utilize the new catchphrase with a constructor for a class. (OOP)
    new MaterialApp(): Here we are making another gadget question called MaterialApp. The MaterialApp gadget makes various helpful things required by a material outline application.
  • home:: In Dart, we can obviously express the name of every parameter inside the capacity/constructor call. The gadget go in as the home parameter is shown first when the application is begun typically.
    new Center(child: new Text('Hello World!')) : We wrap the Text gadget inside a Center gadget so the content gets focused on the screen. The Text gadget is an offspring of the Center gadget. Indeed, gadgets can be settled.


On the off chance that you run the code again and open up your gadget, you ought to show signs of improvement screen now.

Cool! We could demonstrate a monstrous looking content fixated on the gadget screen.

The subsequent stages

How about we step forward at this point. We will get the cryptographic money costs from the CoinMarketCap API. The API restores a JSON cluster. Here is an example reaction from the API:

var currencies = Crypto [ new Crypto(name: "Bitcoin", price_usd: "800.60", percent_change_1h: "-0.7"),

code source : https://github.com/iampawan/CryptoApp/blob/master/lib/data/crypto_data_mock.dart

We will make a demand to the CoinMarketCap API and interpreting the JSON from the application. We should incorporate two or three new bundles to the main.dart record.

import 'dart:async';

import 'dart:convert';

import 'package:flutter/foundation.dart';

import 'package:fluttercrypto/dependency_injection.dart';

import 'package:http/http.dart' as http;

Code Source : https://github.com/iampawan/CryptoApp/blob/master/lib/data/crypto_data.dart

Here's an outline of the new bundles:

dart:async: Provides the Future class, which I will speak more about underneath. 
dart:convert: Provides the json variable we will use to decipher the JSON string reaction. 
package:http/http.dart: Provides the capacity we will use to influence HTTP To get demands. 

How about we add another capacity to the main.dart record that makes a demand to the CoinMarketCap API.

Future List getCurrencies() async {

  String apiUrl = 'https://api.coinmarketcap.com/v1/ticker/?limit=50';

  // Make a HTTP GET request to the CoinMarketCap API.

  // Await basically pauses execution until the get() function returns a Response

  http.Response response = await http.get(apiUrl);

  // Using the JSON class to decode the JSON String

  return JSON.decode(response.body);

}

How about we stroll through the new code

→ Future List : We are essentially saying that the getCurrencies() capacity will restore a List at some point later on. It will influence a HTTP to demand to the CoinMarketCap API and restore a List of monetary forms when done.

The getCurrencies() work is nonconcurrent. In the event that you have some JavaScript encounter, you can consider Futures Promises. I made the pictures beneath to enable you to comprehend Futures in Dart.

async and anticipate :

Anticipate articulations let you compose offbeat code nearly as though it were synchronous. The http.get(url) work is nonconcurrent, restoring a Future Response quickly when it's called. We need to sit tight for the Response so we can interpret the JSON string, however we additionally would prefer not to utilize revolting callbacks.

The anticipate articulation assesses http.get(url), and after that suspends the right now running capacity (getCurrencies()) until the point that the outcome is ready — that is, until the point when the Future has finished.

To utilize anticipate, the code must be in a capacity set apart as offbeat. An async work is a capacity whose body is set apart with an async modifier. When you call an async work, it quickly restores a Future. The body of the capacity is planned for execution later.

You can read more about async and anticipate in Dart here.

→ http.get(url) : Makes a HTTP GET ask for to the CoinMarketCap API. This capacity is offbeat and returns a Future promptly.

JSON.decode(response.body) : Decodes the JSON string reaction.

We should test the getCurrencies() work we just made. We do that by making a call to it in our main capacity and printing the returned an incentive to the support.

void main() async {

  Injector.configure(Flavor.PROD);

  runApp(new MyApp());

}


class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      theme: new ThemeData(

          primarySwatch: Colors.pink,

          primaryColor: defaultTargetPlatform == TargetPlatform.iOS

              ? Colors.grey[100]

              : null),

      home: new HomePage(),

    );

  }

}

On the off chance that you run the code above, you should see the API reaction printed to the reassure.

Indeed, in reality awful things can happen. For instance, you won't not be associated with the web, so the demand to the CoinMarketCap API will fall flat.
In a generation application, you should deal with organize disappointment. You do that by putting the HTTP bring in an attempt… get square.

Working out the UI

Since we have a rundown of monetary standards, we should proceed to build the UI to demonstrate that rundown.

When composing Flutter applications, you'll ordinarily make new gadget classes. A gadget's fundamental occupation is to actualize an assemble work, which portrays the gadget as far as other, bring down level gadgets.

We should make another Widget called CryptoListWidget. Add the code underneath to the base of your main.dart document.

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      theme: new ThemeData(

          primarySwatch: Colors.pink,

          primaryColor: defaultTargetPlatform == TargetPlatform.iOS

              ? Colors.grey[100]

              : null),

      home: new HomePage(),

    );

  }

}

How about we stroll through the new code above:

  • StatelessWidget : You will as a rule make Widgets that are subclasses of either StatelessWidget or StatefulWidget, contingent upon whether your gadget deals with any state. We are utilizing StatelessWidget in light of the fact that we have our information as of now and we won't refresh it in this instructional exercise.
  • last List MaterialColor colors : Variables in a StatelessWidget ought to be final (which means they are steady or don't change). Here we are proclaiming a last factor that holds a rundown of MaterialColors. The underscore () before the variable name makes it private (difficult to reach from different classes).
  • CryptoListWidget(this._currencies) : This is the constructor for our gadget. It allots the rundown of monetary standards we go into the constructor to the _currencies variable.
    build function: The construct strategy restores a lower-level Widget (Text) that portrays how it will look.

How about we supplant the Text gadget in the build work above with another gadget called Scaffold. The Scaffold gadget actualizes the fundamental material plan visual design structure. Supplant the build work above with the one beneath.

@override

  Widget build(BuildContext context) {

    return new Scaffold(

      body: _buildBody(),

      backgroundColor: Colors.grey,

    );

  }

The Scaffold class gives APIs to indicating drawers, skimming an activity catch, base bar, lunch room, et cetera. We will include a drifting activity button later.


You ought to get a notice that _buildBody() isn't characterized for the class CryptoListWidget. We should proceed to make _buildBody() work within the CryptoListWidget class.

Widget _buildBody() {

    return new Container(

      // A top margin of 56.0. A left and right margin of 8.0. And a bottom margin of 0.0.

      margin: const EdgeInsets.fromLTRB(8.0, 56.0, 8.0, 0.0),

      child: new Column(

        // A column widget can have several widgets that are placed in a top down fashion

        children: Widget[

          _getAppTitleWidget(),

          _getListViewWidget()

        ],

      ),

    );

  }

The linguistic structure here ought to be well-known. We are utilizing two new Widgets:

Container widget : A Container widget is only a compartment :) (for different widgets). 


column widget: A Column widget designs a rundown of kid widgetts in the vertical heading. It has a parameter called kids that takes a rundown of widgets. 

How about we make the two capacities we brought in the _buildBody() work. The first is _getAppTitleWidget() .

Widget _getAppTitleWidget() {

    return new Text(

      'Cryptocurrencies',

      style: new TextStyle(

          color: Colors.white,

          fontWeight: FontWeight.bold,

          fontSize: 24.0),

    );

  }

This capacity restores a customary Text widget with a style that makes it strong and white with a text dimension of 24.0.

The content will resemble this when we run the application.

We can't run the application yet on the grounds that we haven't made the other capacity called _getListViewWidget(). How about we rapidly make it utilizing the code underneath.

Widget _getListViewWidget() {

    // We want the ListView to have the flexibility to expand to fill the

    // available space in the vertical axis

    return new Flexible(

        child: new ListView.builder(

            // The number of items to show

            itemCount: _currencies.length,

            // Callback that should return ListView children

            // The index parameter = 0...(itemCount-1)

            itemBuilder: (context, index) {

              // Get the currency at this position

              final Map currency = _currencies[index];


              // Get the icon color. Since x mod y, will always be less than y,

              // this will be within bounds

              final MaterialColor color = _colors[index % _colors.length];


              return _getListItemWidget(currency, color);

            }));

I have added remarks to the code above to enable you to comprehend it.

The _getListViewWidget() restores a ListView widget that is wrapped in a Flexible widget. We utilize the ListView.builder to effectively make the rundown. We go in an itemCount which advises the manufacturer what number of monetary standards to appear.

The itemBuilder callback will be required every thing and you need to restore another widget. In the code above we are calling a capacity called _getListItemWidget() that profits a Widget.

Before we make the _getListItemWidget() work, how about we rapidly make the individual components for the ListView thing gadget. We need every thing in the ListView to resemble this:

In this way, we have three fundamental widgets:

A round symbol gadget with the cash name's first character 
A content gadget with the money name 
A content gadget with the cost and percent change in 60 minutes. 

How about we make the widgets. For straightforwardness purpose, I made a capacity for every one of them. The main capacity called _getLeadingWidget() restores the round symbol with the content.

CircleAvatar _getLeadingWidget(String currencyName, MaterialColor color) {

    return new CircleAvatar(

      backgroundColor: color,

      child: new Text(currencyName[0]),

    );

  }

The widget will resemble this:

The second function called _getTitleWidget restores the Text gadget for the cash name.

The third function called _getSubtitleWidget() restores the Text gadget at the cash current cost and percent change in 1 hour.

Text _getTitleWidget(String currencyName) {

    return new Text(

      currencyName,

      style: new TextStyle(fontWeight: FontWeight.bold),

    );

  }


  Text _getSubtitleWidget(String priceUsd, String percentChange1h) {

    return new Text('\$$priceUsd\n1 hour: $percentChange1h%');

  }

Both of these gadgets should resemble this:

How about we wrap every one of the three gadgets in something many refer to as a ListTile gadget. The ListTile gadget depends on the Material Design List documentation. It demonstrates every one of the three gadgets in this style.

We will make another capacity called _getListTile that profits a ListTile widget.

ListTile _getListTile(Map currency, MaterialColor color) {

    return new ListTile(

      leading: _getLeadingWidget(currency['name'], color),

      title: _getTitleWidget(currency['name']),

      subtitle: _getSubtitleWidget(

          currency['price_usd'], currency['percent_change_1h']),

      isThreeLine: true,

    );

  }

At last, how about we make the _getListItemWidget() . It will restore a Container gadget that has a best cushioning of 5.0 and has a Card gadget youngster. The card gadget has the ListTile returned by _getListTile as it's kid.

Container _getListItemWidget(Map currency, MaterialColor color) {

    // Returns a container widget that has a card child and a top margin of 5.0

    return new Container(

      margin: const EdgeInsets.only(top: 5.0),

      child: new Card(

        child: _getListTile(currency, color),

      ),

    );

  }

The widget will resemble this.

We have effectively finished our CryptoListWidget. However, we need to refresh the primary capacity to demonstrate the recently made widget rather than the Text widget.

void main() async {

  // Bad practice alert :). You should ideally show the UI, and probably a progress view,

  // then when the requests completes, update the UI to show the data.

  List currencies = await getCurrencies();

  print(currencies);

  

  runApp(new MaterialApp(

    home: new CryptoListWidget(currencies),

  ));

}

That is it. You can hit the run catch once more. In the event that everything functions admirably and you are associated with the web, you should a screen that resembles this.

Extremely cool right?

The application you see will be somewhat not the same as the screen capture above:
It doesn't have a drifting activity catch at the base right.

The content shade of the percent change in 1 hour is dark.

I chose not to incorporate them in the instructional exercise. However, you can check the task 8 to perceive how I could accomplish it.

Note: The completed app can be uploaded play store/app store although this is an open source project I will keep updating this project in future.

Summary

In this tutorial, I showed you how to use Flutter to build an app that shows the current price of different cryptocurrencies. I will walk you through the fundamentals of Flutter and Dart.

Proof of Work Done

Sort:  

Hey @iampawan, your contribution was unvoted because we found out that it did not follow the Utopian rules.

Upvote this comment to help Utopian grow its power and help other Open Source contributions like this one.

Want to chat? Join us on Discord.

@utopian-io what is the reason? please explain for my better work in future.

@iampawan you have been caught plagiarizing several content from the web and have been banned accordingly.
Examples include:
https://steemit.com/utopian-io/@iampawan/flutter-building-a-whatsapp-clone-from-scratch
from this source: https://medium.com/@Nash_905/building-whatsapp-ui-with-flutter-io-and-dart-1bb1e83e7439
Another example includes:
https://steemit.com/utopian-io/@iampawan/flutter-backdrop-widget-material-design-2-0
from this source: https://medium.com/@CORDEA/implement-backdrop-with-flutter-73b4c61b1357

Any future contributions from you will be auto-rejected.

Coin Marketplace

STEEM 0.21
TRX 0.24
JST 0.038
BTC 94636.84
ETH 3278.73
USDT 1.00
SBD 3.16