Flutter – Introduction to Package

Flutter – Introduction to Package ”; Previous Next Dart’s way of organizing and sharing a set of functionality is through Package. Dart Package is simply sharable libraries or modules. In general, the Dart Package is same as that of Dart Application except Dart Package does not have application entry point, main. The general structure of Package (consider a demo package, my_demo_package) is as below − lib/src/* − Private Dart code files. lib/my_demo_package.dart − Main Dart code file. It can be imported into an application as − import ”package:my_demo_package/my_demo_package.dart” Other private code file may be exported into the main code file (my_demo_package.dart), if necessary as shown below − export src/my_private_code.dart lib/* − Any number of Dart code files arranged in any custom folder structure. The code can be accessed as, import ”package:my_demo_package/custom_folder/custom_file.dart” pubspec.yaml − Project specification, same as that of application, All Dart code files in the Package are simply Dart classes and it does not have any special requirement for a Dart code to include it in a Package. Types of Packages Since Dart Packages are basically a small collection of similar functionality, it can be categorized based on its functionality. Dart Package Generic Dart code, which can be used in both web and mobile environment. For example, english_words is one such package which contains around 5000 words and has basic utility functions like nouns (list nouns in the English), syllables (specify number of syllables in a word. Flutter Package Generic Dart code, which depends on Flutter framework and can be used only in mobile environment. For example, fluro is a custom router for flutter. It depends on the Flutter framework. Flutter Plugin Generic Dart code, which depends on Flutter framework as well as the underlying platform code (Android SDK or iOS SDK). For example, camera is a plugin to interact with device camera. It depends on the Flutter framework as well as the underlying framework to get access to camera. Using a Dart Package Dart Packages are hosted and published into the live server, https://pub.dartlang.org. Also, Flutter provides simple tool, pub to manage Dart Packages in the application. The steps needed to use as Package is as follows − Include the package name and the version needed into the pubspec.yaml as shown below − dependencies: english_words: ^3.1.5 The latest version number can be found by checking the online server. Install the package into the application by using the following command − flutter packages get While developing in the Android studio, Android Studio detects any change in the pubspec.yaml and displays an Android studio package alert to the developer as shown below − Dart Packages can be installed or updated in Android Studio using the menu options. Import the necessary file using the command shown below and start working − import ”package:english_words/english_words.dart”; Use any method available in the package, nouns.take(50).forEach(print); Here, we have used nouns function to get and print the top 50 words. Develop a Flutter Plugin Package Developing a Flutter Plugin is similar to developing a Dart application or Dart Package. The only exception is that the plugin is going to use System API (Android or iOS) to get the required platform specific functionality. As we have already learned how to access platform code in the previous chapters, let us develop a simple plugin, my_browser to understand the plugin development process. The functionality of the my_browser plugin is to allow the application to open the given website in the platform specific browser. Start Android Studio. Click File → New Flutter Project and select Flutter Plugin option. You can see a Flutter plugin selection window as shown here − Enter my_browser as project name and click Next. Enter the plugin name and other details in the window as shown here − Enter company domain, flutterplugins.tutorialspoint.com in the window shown below and then click on Finish. It will generate a startup code to develop our new plugin. Open my_browser.dart file and write a method, openBrowser to invoke platform specific openBrowser method. Future<void> openBrowser(String urlString) async { try { final int result = await _channel.invokeMethod( ”openBrowser”, <String, String>{ ”url”: urlString } ); } on PlatformException catch (e) { // Unable to open the browser print(e); } } Open MyBrowserPlugin.java file and import the following classes − import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; Here, we have to import library required for opening a browser from Android. Add new private variable mRegistrar of type Registrar in MyBrowserPlugin class. private final Registrar mRegistrar; Here, Registrar is used to get context information of the invoking code. Add a constructor to set Registrar in MyBrowserPlugin class. private MyBrowserPlugin(Registrar registrar) { this.mRegistrar = registrar; } Change registerWith to include our new constructor in MyBrowserPlugin class. public static void registerWith(Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), “my_browser”); MyBrowserPlugin instance = new MyBrowserPlugin(registrar); channel.setMethodCallHandler(instance); } Change the onMethodCall to include openBrowser method in MyBrowserPlugin class. @Override public void onMethodCall(MethodCall call, Result result) { String url = call.argument(“url”); if (call.method.equals(“getPlatformVersion”)) { result.success(“Android ” + android.os.Build.VERSION.RELEASE); } else if (call.method.equals(“openBrowser”)) { openBrowser(call, result, url); } else { result.notImplemented(); } } Write the platform specific openBrowser method to access browser in MyBrowserPlugin class.

Creating Simple Application in Android Studio

Creating Simple Application in Android Studio ”; Previous Next In this chapter, let us create a simple Flutter application to understand the basics of creating a flutter application in the Android Studio. Step 1 − Open Android Studio Step 2 − Create Flutter Project. For this, click File → New → New Flutter Project Step 3 − Select Flutter Application. For this, select Flutter Application and click Next. Step 4 − Configure the application as below and click Next. Project name: hello_app Flutter SDK Path: <path_to_flutter_sdk> Project Location: <path_to_project_folder> Description: Flutter based hello world application Step 5 − Configure Project. Set the company domain as flutterapp.tutorialspoint.com and click Finish. Step 6 − Enter Company domain. Android Studio creates a fully working flutter application with minimal functionality. Let us check the structure of the application and then, change the code to do our task. The structure of the application and its purpose is as follows − Various components of the structure of the application are explained here − android − Auto generated source code to create android application ios − Auto generated source code to create ios application lib − Main folder containing Dart code written using flutter framework ib/main.dart − Entry point of the Flutter application test − Folder containing Dart code to test the flutter application test/widget_test.dart − Sample code .gitignore − Git version control file .metadata − auto generated by the flutter tools .packages − auto generated to track the flutter packages .iml − project file used by Android studio pubspec.yaml − Used by Pub, Flutter package manager pubspec.lock − Auto generated by the Flutter package manager, Pub README.md − Project description file written in Markdown format Step 7 − Replace the dart code in the lib/main.dart file with the below 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: ”Hello World Demo Application”, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: ”Home page”), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: Text( ”Hello World”, ) ), ); } } Let us understand the dart code line by line. Line 1 − imports the flutter package, material. The material is a flutter package to create user interface according to the Material design guidelines specified by Android. Line 3 − This is the entry point of the Flutter application. Calls runApp function and pass it an object of MyApp class. The purpose of the runApp function is to attach the given widget to the screen. Line 5-17 − Widget is used to create UI in flutter framework. StatelessWidget is a widget, which does not maintain any state of the widget. MyApp extends StatelessWidget and overrides its build method. The purpose of the build method is to create a part of the UI of the application. Here, build method uses MaterialApp, a widget to create the root level UI of the application. It has three properties – title, theme and home. title is the title of the application theme is the theme of the widget. Here, we set blue as the overall color of the application using ThemeData class and its property, primarySwatch. home is the inner UI of the application, which we set another widget, MyHomePage Line 19 – 38 − MyHomePage is same as MyApp except it returns Scaffold Widget. Scaffold is a top level widget next to MaterialApp widget used to create UI conforming material design. It has two important properties, appBar to show the header of the application and body to show the actual content of the application. AppBar is another widget to render the header of the application and we have used it in appBar property. In body property, we have used Center widget, which centers it child widget. Text is the final and inner most widget to show the text and it is displayed in the center of the screen. Step 8 − Now, run the application using, Run → Run main.dart Step 9 − Finally, the output of the application is as follows − Print Page Previous Next Advertisements ”;

Flutter – Introduction

Flutter – Introduction ”; Previous Next In general, developing a mobile application is a complex and challenging task. There are many frameworks available to develop a mobile application. Android provides a native framework based on Java language and iOS provides a native framework based on Objective-C / Swift language. However, to develop an application supporting both the OSs, we need to code in two different languages using two different frameworks. To help overcome this complexity, there exists mobile frameworks supporting both OS. These frameworks range from simple HTML based hybrid mobile application framework (which uses HTML for User Interface and JavaScript for application logic) to complex language specific framework (which do the heavy lifting of converting code to native code). Irrespective of their simplicity or complexity, these frameworks always have many disadvantages, one of the main drawback being their slow performance. In this scenario, Flutter – a simple and high performance framework based on Dart language, provides high performance by rendering the UI directly in the operating system’s canvas rather than through native framework. Flutter also offers many ready to use widgets (UI) to create a modern application. These widgets are optimized for mobile environment and designing the application using widgets is as simple as designing HTML. To be specific, Flutter application is itself a widget. Flutter widgets also supports animations and gestures. The application logic is based on reactive programming. Widget may optionally have a state. By changing the state of the widget, Flutter will automatically (reactive programming) compare the widget’s state (old and new) and render the widget with only the necessary changes instead of re-rendering the whole widget. We shall discuss the complete architecture in the coming chapters. Features of Flutter Flutter framework offers the following features to developers − Modern and reactive framework. Uses Dart programming language and it is very easy to learn. Fast development. Beautiful and fluid user interfaces. Huge widget catalog. Runs same UI for multiple platforms. High performance application. Advantages of Flutter Flutter comes with beautiful and customizable widgets for high performance and outstanding mobile application. It fulfills all the custom needs and requirements. Besides these, Flutter offers many more advantages as mentioned below − Dart has a large repository of software packages which lets you to extend the capabilities of your application. Developers need to write just a single code base for both applications (both Android and iOS platforms). Flutter may to be extended to other platform as well in the future. Flutter needs lesser testing. Because of its single code base, it is sufficient if we write automated tests once for both the platforms. Flutter’s simplicity makes it a good candidate for fast development. Its customization capability and extendibility makes it even more powerful. With Flutter, developers has full control over the widgets and its layout. Flutter offers great developer tools, with amazing hot reload. Disadvantages of Flutter Despite its many advantages, flutter has the following drawbacks in it − Since it is coded in Dart language, a developer needs to learn new language (though it is easy to learn). Modern framework tries to separate logic and UI as much as possible but, in Flutter, user interface and logic is intermixed. We can overcome this using smart coding and using high level module to separate user interface and logic. Flutter is yet another framework to create mobile application. Developers are having a hard time in choosing the right development tools in hugely populated segment. Print Page Previous Next Advertisements ”;

Flutter – Quick Guide

Flutter – Quick Guide ”; Previous Next Flutter – Introduction In general, developing a mobile application is a complex and challenging task. There are many frameworks available to develop a mobile application. Android provides a native framework based on Java language and iOS provides a native framework based on Objective-C / Swift language. However, to develop an application supporting both the OSs, we need to code in two different languages using two different frameworks. To help overcome this complexity, there exists mobile frameworks supporting both OS. These frameworks range from simple HTML based hybrid mobile application framework (which uses HTML for User Interface and JavaScript for application logic) to complex language specific framework (which do the heavy lifting of converting code to native code). Irrespective of their simplicity or complexity, these frameworks always have many disadvantages, one of the main drawback being their slow performance. In this scenario, Flutter – a simple and high performance framework based on Dart language, provides high performance by rendering the UI directly in the operating system’s canvas rather than through native framework. Flutter also offers many ready to use widgets (UI) to create a modern application. These widgets are optimized for mobile environment and designing the application using widgets is as simple as designing HTML. To be specific, Flutter application is itself a widget. Flutter widgets also supports animations and gestures. The application logic is based on reactive programming. Widget may optionally have a state. By changing the state of the widget, Flutter will automatically (reactive programming) compare the widget’s state (old and new) and render the widget with only the necessary changes instead of re-rendering the whole widget. We shall discuss the complete architecture in the coming chapters. Features of Flutter Flutter framework offers the following features to developers − Modern and reactive framework. Uses Dart programming language and it is very easy to learn. Fast development. Beautiful and fluid user interfaces. Huge widget catalog. Runs same UI for multiple platforms. High performance application. Advantages of Flutter Flutter comes with beautiful and customizable widgets for high performance and outstanding mobile application. It fulfills all the custom needs and requirements. Besides these, Flutter offers many more advantages as mentioned below − Dart has a large repository of software packages which lets you to extend the capabilities of your application. Developers need to write just a single code base for both applications (both Android and iOS platforms). Flutter may to be extended to other platform as well in the future. Flutter needs lesser testing. Because of its single code base, it is sufficient if we write automated tests once for both the platforms. Flutter’s simplicity makes it a good candidate for fast development. Its customization capability and extendibility makes it even more powerful. With Flutter, developers has full control over the widgets and its layout. Flutter offers great developer tools, with amazing hot reload. Disadvantages of Flutter Despite its many advantages, flutter has the following drawbacks in it − Since it is coded in Dart language, a developer needs to learn new language (though it is easy to learn). Modern framework tries to separate logic and UI as much as possible but, in Flutter, user interface and logic is intermixed. We can overcome this using smart coding and using high level module to separate user interface and logic. Flutter is yet another framework to create mobile application. Developers are having a hard time in choosing the right development tools in hugely populated segment. Flutter – Installation This chapter will guide you through the installation of Flutter on your local computer in detail. Installation in Windows In this section, let us see how to install Flutter SDK and its requirement in a windows system. Step 1 − Go to URL, https://flutter.dev/docs/get-started/install/windows and download the latest Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_windows_v1.2.1-stable.zip. Step 2 − Unzip the zip archive in a folder, say C:flutter Step 3 − Update the system path to include flutter bin directory. Step 4 − Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met. flutter doctor Step 5 − Running the above command will analyze the system and show its report as shown below − Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version 10.0.17134.706], locale en-US) [√] Android toolchain – develop for Android devices (Android SDK version 28.0.3) [√] Android Studio (version 3.2) [√] VS Code, 64-bit edition (version 1.29.1) [!] Connected device ! No devices available ! Doctor found issues in 1 category. The report says that all development tools are available but the device is not connected. We can fix this by connecting an android device through USB or starting an android emulator. Step 6 − Install the latest Android SDK, if reported by flutter doctor Step 7 − Install the latest Android Studio, if reported by flutter doctor Step 8 − Start an android emulator or connect a real android device to the system. Step 9 − Install Flutter and Dart plugin for Android Studio. It provides startup template to create new Flutter application, an option to run and debug Flutter application in the Android studio itself, etc., Open Android Studio. Click File → Settings → Plugins. Select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Restart Android studio. Installation in MacOS To install Flutter on MacOS, you will have to follow the following steps − Step 1 − Go to URL, https://flutter.dev/docs/get-started/install/macos and download latest

Introduction to Dart Programming

Flutter – Introduction to Dart Programming ”; Previous Next Dart is an open-source general-purpose programming language. It is originally developed by Google. Dart is an object-oriented language with C-style syntax. It supports programming concepts like interfaces, classes, unlike other programming languages Dart doesn’t support arrays. Dart collections can be used to replicate data structures such as arrays, generics, and optional typing. The following code shows a simple Dart program − void main() { print(“Dart language is easy to learn”); } Variables and Data types Variable is named storage location and Data types simply refers to the type and size of data associated with variables and functions. Dart uses var keyword to declare the variable. The syntax of var is defined below, var name = ”Dart”; The final and const keyword are used to declare constants. They are defined as below − void main() { final a = 12; const pi = 3.14; print(a); print(pi); } Dart language supports the following data types − Numbers − It is used to represent numeric literals – Integer and Double. Strings − It represents a sequence of characters. String values are specified in either single or double quotes. Booleans − Dart uses the bool keyword to represent Boolean values – true and false. Lists and Maps − It is used to represent a collection of objects. A simple List can be defined as below −. void main() { var list = [1,2,3,4,5]; print(list); } The list shown above produces [1,2,3,4,5] list. Map can be defined as shown here − void main() { var mapping = {”id”: 1,”name”:”Dart”}; print(mapping); } Dynamic − If the variable type is not defined, then its default type is dynamic. The following example illustrates the dynamic type variable − void main() { dynamic name = “Dart”; print(name); } Decision Making and Loops A decision making block evaluates a condition before the instructions are executed. Dart supports If, If..else and switch statements. Loops are used to repeat a block of code until a specific condition is met. Dart supports for, for..in , while and do..while loops. Let us understand a simple example about the usage of control statements and loops − void main() { for( var i = 1 ; i <= 10; i++ ) { if(i%2==0) { print(i); } } } The above code prints the even numbers from 1 to 10. Functions A function is a group of statements that together performs a specific task. Let us look into a simple function in Dart as shown here − void main() { add(3,4); } void add(int a,int b) { int c; c = a+b; print(c); } The above function adds two values and produces 7 as the output. Object Oriented Programming Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class is a blueprint for creating objects. A class definition includes the following − Fields Getters and setters Constructors Functions Now, let us create a simple class using the above definitions − class Employee { String name; //getter method String get emp_name { return name; } //setter method void set emp_name(String name) { this.name = name; } //function definition void result() { print(name); } } void main() { //object creation Employee emp = new Employee(); emp.name = “employee1″; emp.result(); //function call } Print Page Previous Next Advertisements ”;