First Counter App in Flutter

in this post we are learning first counter app in flutter.

First Counter App in Flutter

First Counter App in Flutter :

Create the starter Flutter app

If you don’t see “New Flutter Project” as an option in your IDE, make sure you have the plugins installed for Flutter and Dart.

First Counter App in Flutter

Flutter plugin add

First Counter App in Flutter


vs code plugin add

First Counter App in Flutter

How to code write:
You’ll mostly code write in lib package, lib/main.dart, where the Dart code lives.

Code format:
When pasting code / write code into your app, indentation can become skewed. You can fix this with the following Flutter tools:
1) Android Studio and IntelliJ IDEA: Right-click the code and select Reformat Code with dartfmt.
2) VS Code: Right-click and select Format Document.
3) Terminal: Run flutter format .

import package format / Optimize imports:
add external plugin / package (pubspec.yaml):
import_sorter:
Step: Open the pubspec.yaml -> add the plugin dependencies -> Pub get

First way pub get:
While viewing the pubspec.yaml file in Android Studio’s editor view, click Pub get. This pulls the package into your project.

Second way pub get:
open terminal/console flutter pub get enter

Android studio step: Select Project -> lib package right click -> choose option Optimize imports

import_sorter

First Counter App in Flutter


import_sorter (screenshot 4_1)

First Counter App in Flutter

Create a flutter first counter application, by default create application.
Create first application in android studio below step following:

New Flutter Project

First Counter App in Flutter


first app


first app

First Counter App in Flutter


first app

First Counter App in Flutter

main.dart

import 'package:flutter/material.dart';

/*void main() {
  runApp(const MyApp());
}*/

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

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>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

  • Material
    Material is a visual design language that is standard on mobile and the web. Flutter offers a rich set of Material widgets. It’s a good idea to have a uses-material-design: true entry in the flutter section of your pubspec.yaml file. This will allow you to use more features of Material, such as their set of predefined Icons.

Import package

  • First, we have the import statement. This imports the material.dart file which helps in implementing the Material Design throughout the app and for most of the Dart files that are used for UI design you have to import this package.
    import package (screenshot 1)

import ‘package:flutter/material.dart’;
Material is a standard mobile and web visual design language. Flutter provides a rich set of Material style UI components by default.

main

  • Main is function which has the runApp method containing the first Widget as its argument, in this case, it is called MyApp.
  • main() method that will run automatically, when the application is launched.

=> symbol
=> symbol, it’s a short syntax for a function that contains only one line.
void main() => runApp(const MyApp());
main (screenshot 2)

MyApp

  • The MyApp is class represents the Flutter application, which inherits the StatelessWidget class, which means that the application itself is also a widget.
  • 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.

@override keyword

  • @override keyword which means that you’re overriding that method which already exists in the parent class.

MyApp extends StatelessWidget:
When application data not refresh then extends StatelessWidget.

return MaterialApp(
title: ‘Flutter Demo’,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: ‘Flutter Demo Home Page’),
);
Here counter application data not refresh need so that use widget StatelessWidget.

theme
This property defines the ThemeData widget containing information about different colors, fonts and other theme data that would be used throughout the app. Here, only one property is defined, primarySwatch which stores the color blue. But, in your app, you can define any number of theme properties you want.

title

  • A one-line description used by the device to identify the app for the user. It is not visible, it’s just a system title.

appBar
This property takes the AppBar widget containing a Text widget which displays the title of the app.

home (first launch/display) screen)

  • The widget for the default route of the app.
  • First screen which is launch/show.
  • The home parameter of MaterialApp sets the home page for the Flutter application, which is also a widget.

floatingActionButton
This property takes the FloatingActionButton widget which displays a FAB at the bottom right corner of the screen. The FAB widget takes three properties: onPressed, tooltip & child .

onPressed
The onPressed property is used to call the _incrementCounter method which increments the counter by 1 and rebuilds the widget tree.

tooltip
This property can take a String. The text is displayed when the user long-presses on the button and is used for accessibility, which means that it won’t be displayed in normal circumstances.

Types of main widget:
1) Stateless widget (No lifecycle), like: Text, RaisedButton, Icon Padding, AssetImage. The internal state of those widgets won’t change.
2) Stateful widget, like: Animatable, Scrollable, Image, Form, Checkbox. Those widgets are dynamic and their state may change. When it happens, setState() gets called and the widget is rebuilt.

Stateful widget lifecycle in flutter:
createState()— A method called immediately on a stateful widget. The method should return a widget’s State object
initiate()—The first method called after the widget is created. For example application launch calling direct api.
didChangeDependencies()—Called the first time the widget is built and immediately after initState()
build()—Called only once in a stateless Widget. In a stateful Widget, it’s called every time the UI needs to render the widget. The method should return a widget’s tree
didUpdateWidget()—Called when there are changes to the parent widget changes the widget is forced to redraw its own UI
deactivate()—Called when this object is removed from the tree
dispose()—Deallocates memory for the widget and its state

build()
When Flutter builds a page, it calls the widget’s build method. The main job of the widget is to provide a build() method to describe how to build the UI interface (usually by combining and assembling other basic widgets).

return build()

  • The return of the build() method should be a type Widget, and method build() accepts a required parameter of type BuildContext – even if you don’t actually use that variable inside, you still need to have it as a parameter.
  • The method build() returns a widget called MaterialApp.

Scaffold

  • The home widget will be defined by another widget type called Scaffold.
  • Scaffold is a page scaffold provided in the Material library. It provides a default navigation bar, title, and body attributes that contain the home screen widget tree (same as “component tree”). The widget tree can be very complicated. In the examples later in this book, routes are created by Scaffold by default.

choose child / children:
When It Comes to layouts, We Can Divide Them Into:

  • Widgets that hold only a single child, e.g. Container, SizedBox, Expanded, Padding
  • Widgets that can have multiple children, like: Row, Column or Stack

MyHomePage
This Stateful Widget MyHomePagetakes a constructor containing a key and a title. Here, the title is passed on from the previous class. You can see that the String title is marked final, this is done because the fields in a Widget subclass are always marked final if you do not mark this as a final you will get a warning.
Now, we have the overridden createState method which returns the instance of the class_MyHomePageState.

BuildContext
BuildContext is the part of the widgets in the element tree such that every widget has its BuildContext. We primarily use it for getting a reference to another theme or widget. For instance, if we have the material design element, it is needed to reference it to the scaffold. We can retrieve it through the Scaffold. of(context) method.

setState

  • setState is one of state management pattern in flutter.
  • Calls setState() to update the UI. If remove the setState can not data refresh your screen.
  • The State is the information that can be read synchronously when the widget is built and might change during the lifetime of the widget.

_MyHomePageState
_MyHomePageState is a State class. Because we only need to maintain a click counter, we define a _counter state:

void _incrementCounter() {
//setState is used to rebuild the widget tree.
setState(() {
_counter++;
});
}

In this class at first, a private integer variable _counter is initialized to zero. After that, we have a private void method defined called _incrementCounter.

When the button is clicked, this function will be called. The function of _incrementCounter is to increment _counter first, and then call the setState method. The function of the setState method is to notify the Flutter framework that a state has changed.

  • After the Flutter framework receives the notification, it will execute the build method to rebuild the interface according to the new state. Flutter has optimized this method to make the re-execution fast , So you can rebuild anything that needs to be updated without modifying each widget separately.
  • The logic of building the UI interface is in the build method. When MyHomePage is created for the first time, the _MyHomePageState class will be created. When the initialization is completed, the Flutter framework will call the widget’s build method to build the widget tree, and finally render the widget tree to the device screen superior.
  • Scaffold is a page scaffold provided in the Material library. It provides a default navigation bar, title, and body attributes that contain the home screen widget tree (same as “component tree”). The widget tree can be very complicated. In the examples later in this book, routes are created by Scaffold by default.
  • The component tree of the body contains a Center component, and Center can align its sub-component tree to the center of the screen.
    the Center subcomponent is a Column component, and the function of Column is to arrange all its subcomponents in order along the vertical direction of the screen.
  • The Column subcomponent is two Texts, and the first Text displays the fixed text “You have pushed the button this many times:”, the second Text displays the value of the _counter state.
  • floatingActionButton is the floating button with “+” in the lower right corner of the page. Its onPressed attribute accepts a callback function to handle the click event. In this example, the _incrementCounter method is directly used as its processing function.

flutter_testing
Counter App in Flutter with unit, widget and integration tests.
1) A unit test tests a single function, method, or class.
2) A widget test (in other UI frameworks referred to as component test) tests a single widget.
3) An integration test tests a complete app or a large part of an app.

  • The MyApp extends StatelessWidget, which makes the app itself a widget. In Flutter, almost everything is a widget, including alignment, padding, and layout.

Flutter Tools
Flutter provides us with some useful tools, like:

  • Hot reload
  • It reloads an app in an instant. This feature comes in handy when modifying layouts. Make some changes to a view, click the thunder icon and the new version of your view is visible in a blink of an eye. An important thing to keep in mind, though, is that Flutter’s hot reload is not supported in all the cases.
    Save the file [Command + S (for MAC), or Ctrl + S (for Windows)].
  • Dart analysis: it’s a very handy tool for finding potential errors and warnings in the Dart code and we used it all a lot during the development.
  • Automatic code formatting in Android Studio (or InteliJ) is one of those features you use all the time. To trigger the formatting, just right-click in the code or on a package and select “Reformat Code with dartfmt”.
  • Flutter widget inspector: it is used for finding a selected widget in a widget tree and deeper in the code. We haven’t used it that much, but it may be practical, especially for larger apps.

How does this work
In this counter application, every time you click the floating button with a “+” sign in the lower right corner, the number in the center of the screen will increase by 1.

Very good, we have read the source code of the Counter example. Now, let us review the execution flow of the entire application:

When the floatingActionButton button in the lower right corner is clicked, the _incrementCounter method will be called.
In the _incrementCounter method, the _counter state is incremented first.
Then setState will notify the Flutter framework that the state has changed.
The Flutter framework will call the build method to rebuild the UI in the new state, and finally display it on the device screen.

Default folders and files structure flutter application
Android

  • The Android folder contains files and folders required for running the application on an Android operating system. These files and folders are autogenerated during the creation of the flutter project. It’s recommended that these folders and files are left as is.
  • The android folder’s primary sub-folders are the res folder and AndroidManifest.xml file. The res folder contains non-programmable resources required for the application, like icons, images, and fonts, while the AndroidManifest.xml file contains information needed by the application SDK.

iOS
Similar to the Android folder, this folder contains the iOS related files and code(s) for the application.

pubspec.yaml file:

  • It is the configuration file of the project that utilizes a lot while working with the Flutter project. It enables us to monitor how our application operates. It also enables us to configure the constraints for the application. This file includes:
  • Project Assets
  • Project Dependencies
  • Project common settings like project version, description, and name.

.idea
The .idea folder will contain settings related to the code editor you are using to build the application. These settings are specific to the current project. However, you could specify default project settings that all created applications will depict.

Lib
This is the most important folder in the project, used to write most of the dart code. By default, the lib folder contains the main.dart file, which is the application’s entry point. This configuration, however, can be changed.

.gitignore
The gitignore file store files are hidden from the IDE, which needs to be ignored when a project is uploaded to version control platforms like GitHub.

.metadata
Like the .gitignore, this file is also hidden. It contains metadata required by the flutter tool to track the flutter project.

.packages
Since flutter is a framework, and it comes with numerous packages and libraries. The .packages file holds the path to every package and library used in the project. Changes should not be made to this file by programmers.

README
This markdown file is used to describe your application in the GitHub repository. You can include what your project does and the dependencies it uses in this file.

Test
As the name suggests this folder is used to store and manage testing codes for the application. Like the Lib Folder, the Test Folder has only one file by default.

Root
These are configuration files which are used by various IDE’s and language tools.

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in