Latest Posts

How to send email using php

We are discussing how to send email using PHP in this article. In order to do this we are using PHP mail...

Create Your First React JS Application

ContentInstalling NPM (Node Package Manager)Installing create-react-app PackageCreate your react applicationInstalling packages and run your application In the previous...

What is React JS? Learn Fundamentals

ContentIntroduction to React JSKey features of React JSJSXVirtual DOMSummary Introduction to React JS React JS...

Web Development Basics

ContentWhat is Web DevelopmentWeb Development RolesWeb DesignerFront-End DeveloperBack-End DeveloperFull-Stack DeveloperWhat does a web developer do?AnalysisCode ReviewMentoringMaintenanceMeetingsDo you need a degree to...

Create Your First Flutter App

Flutter is a new Open Source framework created by Google that focuses on the creation of cross platform applications. Flutter primarily targets iOS and Android, but is increasingly adding support for desktop platforms too.

In this article, we’re going to create our first application using flutter.

Note

Flutter apps are built using the Dart programming language. If you’re new to Dart, you may want to start by getting a general overview of the language first.

Installing Flutter

We can install Flutter on our machine in a variety of ways. The easiest way to get started is to download the installer from the Flutter website.

- Advertisement -

You can find setup instructions for:

macOS
Windows
Linux

In order to developing with flutter, you need to have a flutter supported IDE. I’d recommend that you either use Android Studio / IntelliJ or Visual Studio Code for your Flutter development. Android Studio offers an integrated, feature-rich IDE with support for Flutter, whereas VSCode offers more lightweight, but functional support.

Android Studio

To install the Flutter plugin for Android Studio, open up the plugin preferences using Preferences > Plugins (macOS) or File > Settings > Plugins (Windows/Linux). From there, search for the Flutter plugin within the repository list and hit install.

- Advertisement -

You can find the plugin here.

Visual Studio

To install the Flutter plugin for Visual Studio Code, search the store for “Flutter” or click Install from the this page.

Creating a new Flutter Project

Assuming that you’ve installed Flutter and have the appropriate dependencies (Android Studio/XCode) installed, we can go ahead and create a new Flutter project.

Once again, this can be done in different ways, but I find the easiest ways are to do it via the Terminal or VS Code. Let’s use the terminal in this scenario:

$ flutter create hello_world
$ cd hello_world
$ code .

Launching the project

As promised, above code will go ahead and create a new Flutter project for us and open it up inside of Visual Studio Code. We can then open this using the Flutter plugin for VS Code.

- Advertisement -

Hit the “Debug” section of the editor (or F5) and click “Play” to add a new configuration.

Select “Dart & Flutter” from the dropdown and then choose the device/simulator you’d like to use. I’ve selected the my android phone for this. We should then see our demo application:

Material

We’ve created our first Flutter application and we have it running on a device or an emulator. Let’s take a look at the code that makes this all work. Head to lib/main.dart and you should see the following starter code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

This code may seem little complex at first. Let’s go through the each widget. Let’s start with the MyApp widget.

MyApp

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

First, we are importing the Material package from Flutter. This will give Material Design look to our application and access to the Material style widgets and functionality.

Then we are registering the MyApp as the main widget of the application using runApp() method.

Inside of MyApp, we’re returning a build method of type Widget which returns a MaterialApp. The MaterialApp holds metadata such as current ThemeData, the application title, the current home route, and so on.

Note

Here we could use the iOS styled CupertinoApp or a custom style with WidgetsApp instead of MaterialApp.

MyHomePage

Next widget is MyHomePage widget which is a StatefulWidget. Basically, this has two classes. First class defines the widget.

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Then there is another widget which contains the State for the above widget and the build method. This is similar to the render method of JSX.

One of the more important things to consider with the above example is the fact that we’re overriding the createState method to provide our own way of managing state:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
 }
}

The _counter state can therefore be changed with setState(). Next, we define the build method which creates a Scaffold for our application that contains an appBar and a body.

The Scaffold class can be thought of as a top level container when using MaterialApp. This allows us to easily add navigation bars, floating action buttons, drawers, avoid notches, and much more.

Whenever we call setState(), the widget’s build method is also called, thus, updating the view/redrawing with new state. In our example, you can see that we’re making this call to setState within the FloatingActionButton via the onPressed: _incrementCounter function.

Latest Posts

How to send email using php

We are discussing how to send email using PHP in this article. In order to do this we are using PHP mail...

Create Your First React JS Application

ContentInstalling NPM (Node Package Manager)Installing create-react-app PackageCreate your react applicationInstalling packages and run your application In the previous...

What is React JS? Learn Fundamentals

ContentIntroduction to React JSKey features of React JSJSXVirtual DOMSummary Introduction to React JS React JS...

Web Development Basics

ContentWhat is Web DevelopmentWeb Development RolesWeb DesignerFront-End DeveloperBack-End DeveloperFull-Stack DeveloperWhat does a web developer do?AnalysisCode ReviewMentoringMaintenanceMeetingsDo you need a degree to...

Don't Miss

Stay in touch

To be updated with all the latest news, offers and special announcements.