Flutter – Introduction to Gestures

Flutter – Introduction to Gestures ”; Previous Next Gestures are primarily a way for a user to interact with a mobile (or any touch based device) application. Gestures are generally defined as any physical action / movement of a user in the intention of activating a specific control of the mobile device. Gestures are as simple as tapping the screen of the mobile device to more complex actions used in gaming applications. Some of the widely used gestures are mentioned here − Tap − Touching the surface of the device with fingertip for a short period and then releasing the fingertip. Double Tap − Tapping twice in a short time. Drag − Touching the surface of the device with fingertip and then moving the fingertip in a steady manner and then finally releasing the fingertip. Flick − Similar to dragging, but doing it in a speeder way. Pinch − Pinching the surface of the device using two fingers. Spread/Zoom − Opposite of pinching. Panning − Touching the surface of the device with fingertip and moving it in any direction without releasing the fingertip. Flutter provides an excellent support for all type of gestures through its exclusive widget, GestureDetector. GestureDetector is a non-visual widget primarily used for detecting the user’s gesture. To identify a gesture targeted on a widget, the widget can be placed inside GestureDetector widget. GestureDetector will capture the gesture and dispatch multiple events based on the gesture. Some of the gestures and the corresponding events are given below − Tap onTapDown onTapUp onTap onTapCancel Double tap onDoubleTap Long press onLongPress Vertical drag onVerticalDragStart onVerticalDragUpdate onVerticalDragEnd Horizontal drag onHorizontalDragStart onHorizontalDragUpdate onHorizontalDragEnd Pan onPanStart onPanUpdate onPanEnd Now, let us modify the hello world application to include gesture detection feature and try to understand the concept. Change the body content of the MyHomePage widget as shown below − body: Center( child: GestureDetector( onTap: () { _showDialog(context); }, child: Text( ”Hello World”, ) ) ), Observe that here we have placed the GestureDetector widget above the Text widget in the widget hierarchy, captured the onTap event and then finally shown a dialog window. Implement the *_showDialog* function to present a dialog when user tabs the hello world message. It uses the generic showDialog and AlertDialog widget to create a new dialog widget. The code is shown below − // user defined function void _showDialog(BuildContext context) { // flutter defined function showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( title: new Text(“Message”), content: new Text(“Hello World”), actions: <Widget>[ new FlatButton( child: new Text(“Close”), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } The application will reload in the device using Hot Reload feature. Now, simply click the message, Hello World and it will show the dialog as below − Now, close the dialog by clicking the close option in the dialog. The complete code (main.dart) is as follows − 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; // user defined function void _showDialog(BuildContext context) { // flutter defined function showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( title: new Text(“Message”), content: new Text(“Hello World”), actions: <Widget>[ new FlatButton( child: new Text(“Close”), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(this.title),), body: Center( child: GestureDetector( onTap: () { _showDialog(context); }, child: Text( ”Hello World”, ) ) ), ); } } Finally, Flutter also provides a low-level gesture detection mechanism through Listener widget. It will detect all user interactions and then dispatches the following events − PointerDownEvent PointerMoveEvent PointerUpEvent PointerCancelEvent Flutter also provides a small set of widgets to do specific as well as advanced gestures. The widgets are listed below − Dismissible − Supports flick gesture to dismiss the widget. Draggable − Supports drag gesture to move the widget. LongPressDraggable − Supports drag gesture to move a widget, when its parent widget is also draggable. DragTarget − Accepts any Draggable widget IgnorePointer − Hides the widget and its children from the gesture detection process. AbsorbPointer − Stops the gesture detection process itself and so any overlapping widget also can not able to participate in the gesture detection process and hence, no event is raised. Scrollable − Support scrolling of the content available inside the widget. Print Page Previous Next Advertisements ”;

Flutter – Conclusion

Flutter – Conclusion ”; Previous Next Flutter framework does a great job by providing an excellent framework to build mobile applications in a truly platform independent way. By providing simplicity in the development process, high performance in the resulting mobile application, rich and relevant user interface for both Android and iOS platform, Flutter framework will surely enable a lot of new developers to develop high performance and feature-full mobile application in the near future. Print Page Previous Next Advertisements ”;

Flutter – Introduction to Widgets

Flutter – Introduction to Widgets ”; Previous Next As we learned in the earlier chapter, widgets are everything in Flutter framework. We have already learned how to create new widgets in previous chapters. In this chapter, let us understand the actual concept behind creating the widgets and the different type of widgets available in Flutter framework. Let us check the Hello World application’s MyHomePage widget. The code for this purpose is as given below − 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”,)), ); } } Here, we have created a new widget by extending StatelessWidget. Note that the StatelessWidget only requires a single method build to be implemented in its derived class. The build method gets the context environment necessary to build the widgets through BuildContext parameter and returns the widget it builds. In the code, we have used title as one of the constructor argument and also used Key as another argument. The title is used to display the title and Key is used to identify the widget in the build environment. Here, the build method calls the build method of Scaffold, which in turn calls the build method of AppBar and Center to build its user interface. Finally, Center build method calls Text build method. For a better understanding, the visual representation of the same is given below − Widget Build Visualization In Flutter, widgets can be grouped into multiple categories based on their features, as listed below − Platform specific widgets Layout widgets State maintenance widgets Platform independent / basic widgets Let us discuss each of them in detail now. Platform specific widgets Flutter has widgets specific to a particular platform – Android or iOS. Android specific widgets are designed in accordance with Material design guideline by Android OS. Android specific widgets are called as Material widgets. iOS specific widgets are designed in accordance with Human Interface Guidelines by Apple and they are called as Cupertino widgets. Some of the most used material widgets are as follows − Scaffold AppBar BottomNavigationBar TabBar TabBarView ListTile RaisedButton FloatingActionButton FlatButton IconButton DropdownButton PopupMenuButton ButtonBar TextField Checkbox Radio Switch Slider Date & Time Pickers SimpleDialog AlertDialog Some of the most used Cupertino widgets are as follows − CupertinoButton CupertinoPicker CupertinoDatePicker CupertinoTimerPicker CupertinoNavigationBar CupertinoTabBar CupertinoTabScaffold CupertinoTabView CupertinoTextField CupertinoDialog CupertinoDialogAction CupertinoFullscreenDialogTransition CupertinoPageScaffold CupertinoPageTransition CupertinoActionSheet CupertinoActivityIndicator CupertinoAlertDialog CupertinoPopupSurface CupertinoSlider Layout widgets In Flutter, a widget can be created by composing one or more widgets. To compose multiple widgets into a single widget, Flutter provides large number of widgets with layout feature. For example, the child widget can be centered using Center widget. Some of the popular layout widgets are as follows − Container − A rectangular box decorated using BoxDecoration widgets with background, border and shadow. Center − Center its child widget. Row − Arrange its children in the horizontal direction. Column − Arrange its children in the vertical direction. Stack − Arrange one above the another. We will check the layout widgets in detail in the upcoming Introduction to layout widgets chapter. State maintenance widgets In Flutter, all widgets are either derived from StatelessWidget or StatefulWidget. Widget derived from StatelessWidget does not have any state information but it may contain widget derived from StatefulWidget. The dynamic nature of the application is through interactive behavior of the widgets and the state changes during interaction. For example, tapping a counter button will increase / decrease the internal state of the counter by one and reactive nature of the Flutter widget will auto re-render the widget using new state information. We will learn the concept of StatefulWidget widgets in detail in the upcoming State management chapter. Platform independent / basic widgets Flutter provides large number of basic widgets to create simple as well as complex user interface in a platform independent manner. Let us see some of the basic widgets in this chapter. Text Text widget is used to display a piece of string. The style of the string can be set by using style property and TextStyle class. The sample code for this purpose is as follows − Text(”Hello World!”, style: TextStyle(fontWeight: FontWeight.bold)) Text widget has a special constructor, Text.rich, which accepts the child of type TextSpan to specify the string with different style. TextSpan widget is recursive in nature and it accepts TextSpan as its children. The sample code for this purpose is as follows − Text.rich( TextSpan( children: <TextSpan>[ TextSpan(text: “Hello “, style: TextStyle(fontStyle: FontStyle.italic)), TextSpan(text: “World”, style: TextStyle(fontWeight: FontWeight.bold)), ], ), ) The most important properties of the Text widget are as follows − maxLines, int − Maximum number of lines to show overflow, TextOverFlow − Specify how visual overflow is handled using TextOverFlow class style, TextStyle − Specify the style of the string using TextStyle class textAlign, TextAlign − Alignment of the text like right, left, justify, etc., using TextAlign class textDirection, TextDirection − Direction of text to flow, either left-to-right or right-to-left Image Image widget is used to display an image in the application. Image widget provides different constructors to load images from multiple sources and they are as follows − Image − Generic image loader using ImageProvider

Flutter – Internationalization

Flutter – Internationalization ”; Previous Next Nowadays, mobile applications are used by customers from different countries and as a result, applications are required to display the content in different languages. Enabling an application to work in multiple languages is called Internationalizing the application. For an application to work in different languages, it should first find the current locale of the system in which the application is running and then need to show it’s content in that particular locale, and this process is called Localization. Flutter framework provides three base classes for localization and extensive utility classes derived from base classes to localize an application. The base classes are as follows − Locale − Locale is a class used to identify the user’s language. For example, en-us identifies the American English and it can be created as. Locale en_locale = Locale(”en”, ”US”) Here, the first argument is language code and the second argument is country code. Another example of creating Argentina Spanish (es-ar) locale is as follows − Locale es_locale = Locale(”es”, ”AR”) Localizations − Localizations is a generic widget used to set the Locale and the localized resources of its child. class CustomLocalizations { CustomLocalizations(this.locale); final Locale locale; static CustomLocalizations of(BuildContext context) { return Localizations.of<CustomLocalizations>(context, CustomLocalizations); } static Map<String, Map<String, String>> _resources = { ”en”: { ”title”: ”Demo”, ”message”: ”Hello World” }, ”es”: { ”title”: ”Manifestación”, ”message”: ”Hola Mundo”, }, }; String get title { return _resources[locale.languageCode][”title”]; } String get message { return _resources[locale.languageCode][”message”]; } } Here, CustomLocalizations is a new custom class created specifically to get certain localized content (title and message) for the widget. of method uses the Localizations class to return new CustomLocalizations class. LocalizationsDelegate<T> − LocalizationsDelegate<T> is a factory class through which Localizations widget is loaded. It has three over-ridable methods − isSupported − Accepts a locale and return whether the specified locale is supported or not. @override bool isSupported(Locale locale) => [”en”, ”es”].contains(locale.languageCode); Here, the delegate works for en and es locale only. load − Accepts a locale and start loading the resources for the specified locale. @override Future<CustomLocalizations> load(Locale locale) { return SynchronousFuture<CustomLocalizations>(CustomLocalizations(locale)); } Here, load method returns CustomLocalizations. The returned CustomLocalizations can be used to get values of title and message in both English and Spanish shouldReload − Specifies whether reloading of CustomLocalizations is necessary when its Localizations widget is rebuild. @override bool shouldReload(CustomLocalizationsDelegate old) => false; The complete code of CustomLocalizationDelegate is as follows − class CustomLocalizationsDelegate extends LocalizationsDelegate<CustomLocalizations> { const CustomLocalizationsDelegate(); @override bool isSupported(Locale locale) => [”en”, ”es”].contains(locale.languageCode); @override Future<CustomLocalizations> load(Locale locale) { return SynchronousFuture<CustomLocalizations>(CustomLocalizations(locale)); } @override bool shouldReload(CustomLocalizationsDelegate old) => false; } In general, Flutter applications are based on two root level widgets, MaterialApp or WidgetsApp. Flutter provides ready made localization for both widgets and they are MaterialLocalizations and WidgetsLocaliations. Further, Flutter also provides delegates to load MaterialLocalizations and WidgetsLocaliations and they are GlobalMaterialLocalizations.delegate and GlobalWidgetsLocalizations.delegate respectively. Let us create a simple internationalization enabled application to test and understand the concept. Create a new flutter application, flutter_localization_app. Flutter supports the internationalization using exclusive flutter package, flutter_localizations. The idea is to separate the localized content from the main SDK. Open the pubspec.yaml and add below code to enable the internationalization package − dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter Android studio will display the following alert that the pubspec.yaml is updated. Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application. Import flutter_localizations package in the main.dart as follows − import ”package:flutter_localizations/flutter_localizations.dart”; import ”package:flutter/foundation.dart” show SynchronousFuture; Here, the purpose of SynchronousFuture is to load the custom localizations synchronously. Create a custom localizations and its corresponding delegate as specified below − class CustomLocalizations { CustomLocalizations(this.locale); final Locale locale; static CustomLocalizations of(BuildContext context) { return Localizations.of<CustomLocalizations>(context, CustomLocalizations); } static Map<String, Map<String, String>> _resources = { ”en”: { ”title”: ”Demo”, ”message”: ”Hello World” }, ”es”: { ”title”: ”Manifestación”, ”message”: ”Hola Mundo”, }, }; String get title { return _resources[locale.languageCode][”title”]; } String get message { return _resources[locale.languageCode][”message”]; } } class CustomLocalizationsDelegate extends LocalizationsDelegate<CustomLocalizations> { const CustomLocalizationsDelegate(); @override bool isSupported(Locale locale) => [”en”, ”es”].contains(locale.languageCode); @override Future<CustomLocalizations> load(Locale locale) { return SynchronousFuture<CustomLocalizations>(CustomLocalizations(locale)); } @override bool shouldReload(CustomLocalizationsDelegate old) => false; } Here, CustomLocalizations is created to support localization for title and message in the application and CustomLocalizationsDelegate is used to load CustomLocalizations. Add delegates for MaterialApp, WidgetsApp and CustomLocalization using MaterialApp properties, localizationsDelegates and supportedLocales as specified below − localizationsDelegates: [ const CustomLocalizationsDelegate(), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ const Locale(”en”, ””), const Locale(”es”, ””), ], Use CustomLocalizations method, of to get the localized value of title and message and use it in appropriate place as specified below − 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(CustomLocalizations .of(context) .title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( CustomLocalizations .of(context) .message, ), ], ), ), ); } } Here, we have modified the MyHomePage class from StatefulWidget to StatelessWidget for simplicity reason and used the CustomLocalizations to

Flutter – State Management

Flutter – State Management ”; Previous Next Managing state in an application is one of the most important and necessary process in the life cycle of an application. Let us consider a simple shopping cart application. User will login using their credentials into the application. Once user is logged in, the application should persist the logged in user detail in all the screen. Again, when the user selects a product and saved into a cart, the cart information should persist between the pages until the user checked out the cart. User and their cart information at any instance is called the state of the application at that instance. A state management can be divided into two categories based on the duration the particular state lasts in an application. Ephemeral − Last for a few seconds like the current state of an animation or a single page like current rating of a product. Flutter supports its through StatefulWidget. app state − Last for entire application like logged in user details, cart information, etc., Flutter supports its through scoped_model. Navigation and Routing In any application, navigating from one page / screen to another defines the work flow of the application. The way that the navigation of an application is handled is called Routing. Flutter provides a basic routing class – MaterialPageRoute and two methods – Navigator.push and Navigator.pop, to define the work flow of an application. MaterialPageRoute MaterialPageRoute is a widget used to render its UI by replacing the entire screen with a platform specific animation. MaterialPageRoute(builder: (context) => Widget()) Here, builder will accepts a function to build its content by suppling the current context of the application. Navigation.push Navigation.push is used to navigate to new screen using MaterialPageRoute widget. Navigator.push( context, MaterialPageRoute(builder: (context) => Widget()), ); Navigation.pop Navigation.pop is used to navigate to previous screen. Navigator.push(context); Let us create a new application to better understand the navigation concept. Create a new Flutter application in Android studio, product_nav_app Copy the assets folder from product_nav_app to product_state_app and add assets inside the pubspec.yaml file. flutter: assets: – assets/appimages/floppy.png – assets/appimages/iphone.png – assets/appimages/laptop.png – assets/appimages/pendrive.png – assets/appimages/pixel.png – assets/appimages/tablet.png Replace the default startup code (main.dart) with our startup 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( primarySwatch: Colors.blue, ), home: MyHomePage( title: ”Product state demo 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 create a Product class to organize the product information. class Product { final String name; final String description; final int price; final String image; Product(this.name, this.description, this.price, this.image); } Let us write a method getProducts in the Product class to generate our dummy product records. static List<Product> getProducts() { List<Product> items = <Product>[]; items.add( Product( “Pixel”, “Pixel is the most feature-full phone ever”, 800, “pixel.png” ) ); items.add( Product( “Laptop”, “Laptop is most productive development tool”, 2000, “ laptop.png” ) ); items.add( Product( “Tablet”, “Tablet is the most useful device ever for meeting”, 1500, “tablet.png” ) ); items.add( Product( “Pendrive”, “Pendrive is useful storage medium”, 100, “pendrive.png” ) ); items.add( Product( “Floppy Drive”, “Floppy drive is useful rescue storage medium”, 20, “floppy.png” ) ); return items; } import product.dart in main.dart import ”Product.dart”; Let us include our new widget, RatingBox. class RatingBox extends StatefulWidget { @override _RatingBoxState createState() =>_RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState(() { _rating = 1; }); } void _setRatingAsTwo() { setState(() { _rating = 2; }); } void _setRatingAsThree() { setState(() { _rating = 3; }); } Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 1? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 2? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 3 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } } Let us modify our ProductBox widget to work with our new Product class. class ProductBox extends StatelessWidget { ProductBox({Key key, this.item}) : super(key: key); final Product item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset(“assets/appimages/” + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[

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

Flutter – Installation

Flutter – Installation ”; Previous Next 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 Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_macos_v1.2.1- stable.zip. Step 2 − Unzip the zip archive in a folder, say /path/to/flutter Step 3 − Update the system path to include flutter bin directory (in ~/.bashrc file). > export PATH = “$PATH:/path/to/flutter/bin” Step 4 − Enable the updated path in the current session using below command and then verify it as well. source ~/.bashrc source $HOME/.bash_profile echo $PATH Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met. It is similar to the Windows counterpart. Step 5 − Install latest XCode, if reported by flutter doctor Step 6 − Install latest Android SDK, if reported by flutter doctor Step 7 − Install latest Android Studio, if reported by flutter doctor Step 8 − Start an android emulator or connect a real android device to the system to develop android application. Step 9 − Open iOS simulator or connect a real iPhone device to the system to develop iOS application. Step 10 − Install Flutter and Dart plugin for Android Studio. It provides the startup template to create a new Flutter application, option to run and debug Flutter application in the Android studio itself, etc., Open Android Studio Click Preferences → Plugins Select the Flutter plugin and click Install Click Yes when prompted to install the Dart plugin. Restart Android studio. Print Page Previous Next Advertisements ”;

Flutter – Development Tools

Flutter – Development Tools ”; Previous Next This chapter explains about Flutter development tools in detail. The first stable release of the cross-platform development toolkit was released on December 4th, 2018, Flutter 1.0. Well, Google is continuously working on the improvements and strengthening the Flutter framework with different development tools. Widget Sets Google updated for Material and Cupertino widget sets to provide pixel-perfect quality in the components design. The upcoming version of flutter 1.2 will be designed to support desktop keyboard events and mouse hover support. Flutter Development with Visual Studio Code Visual Studio Code supports flutter development and provides extensive shortcuts for fast and efficient development. Some of the key features provided by Visual Studio Code for flutter development are listed below − Code assist – When you want to check for options, you can use Ctrl+Space to get a list of code completion options. Quick fix – Ctrl+. is quick fix tool to help in fixing the code. Shortcuts while Coding. Provides detailed documentation in comments. Debugging shortcuts. Hot restarts. Dart DevTools We can use Android Studio or Visual Studio Code, or any other IDE to write our code and install plugins. Google’s development team has been working on yet another development tool called Dart DevTools It is a web-based programming suite. It supports both Android and iOS platforms. It is based on time line view so developers can easily analyze their applications. Install DevTools To install DevTools run the following command in your console − flutter packages pub global activate devtools Now you can see the following output − Resolving dependencies… + args 1.5.1 + async 2.2.0 + charcode 1.1.2 + codemirror 0.5.3+5.44.0 + collection 1.14.11 + convert 2.1.1 + devtools 0.0.16 + devtools_server 0.0.2 + http 0.12.0+2 + http_parser 3.1.3 + intl 0.15.8 + js 0.6.1+1 + meta 1.1.7 + mime 0.9.6+2 ……………… ……………… Installed executable devtools. Activated devtools 0.0.16. Run Server You can run the DevTools server using the following command − flutter packages pub global run devtools Now, you will get a response similar to this, Serving DevTools at http://127.0.0.1:9100 Start Your Application Go to your application, open simulator and run using the following command − flutter run –observatory-port=9200 Now, you are connected to DevTools. Start DevTools in Browser Now access the below url in the browser, to start DevTools − http://localhost:9100/?port=9200 You will get a response as shown below − Flutter SDK To update Flutter SDK, use the following command − flutter upgrade You can see an output as shown below − To upgrade Flutter packages, use the following command − flutter packages upgrade You could see the following response, Running “flutter packages upgrade” in my_app… 7.4s Flutter Inspector It is used to explore flutter widget trees. To achieve this, run the below command in your console, flutter run –track-widget-creation You can see an output as shown below − Launching lib/main.dart on iPhone X in debug mode… ─Assembling Flutter resources… 3.6s Compiling, linking and signing… 6.8s Xcode build done. 14.2s 2,904ms (!) To hot reload changes while running, press “r”. To hot restart (and rebuild state), press “R”. An Observatory debugger and profiler on iPhone X is available at: http://127.0.0.1:50399/ For a more detailed help message, press “h”. To detach, press “d”; to quit, press “q”. Now go to the url, http://127.0.0.1:50399/ you could see the following result − Print Page Previous Next Advertisements ”;