Lecture 9 - Mobile App Development - Flutter Database

Document Details

FrugalCarnelian7501

Uploaded by FrugalCarnelian7501

Dr. Samah Adel

Tags

flutter database mobile app development database concepts flutter programming

Summary

This lecture covers Flutter database concepts, including SQLite and Firebase. It details how to use these database solutions in mobile application development using Flutter. It also discusses the use of animations to enhance user experience.

Full Transcript

Mobile Application Development Lec. 9 Dr. Samah Adel Flutter Database Concepts Introduction to Databases Definition: Organized collection of data for storage, manipulation, and access. Structure: Data is organized into rows, columns, tables, and indexes. Usage: Store various types of da...

Mobile Application Development Lec. 9 Dr. Samah Adel Flutter Database Concepts Introduction to Databases Definition: Organized collection of data for storage, manipulation, and access. Structure: Data is organized into rows, columns, tables, and indexes. Usage: Store various types of data like text, images, files, etc. Database Packages in Flutter Flutter offers several packages for database integration. Popular packages: sqflite: SQLite database management. Advantages: Ideal for local storage, lightweight, and efficient for offline apps. Use cases: Storing user preferences, caching, or small app-specific databases. Firebase: Cloud-based database. Advantages: Real-time data synchronization, scalable, and easy to integrate with Firebase ecosystem services. Use cases: Chat applications, collaborative tools, and apps requiring real- time updates. SQLite Database SQLite: Lightweight, server-less relational database. Features: Self-contained. Zero-configuration. Transactional SQL engine. Flutter uses the sqflite plugin to interact with SQLite. Steps to Use SQLite in Flutter 1. Create a Project: Add dependencies to pubspec.yaml: Necessary to include packages for SQLite operations (sqflite) and determining file paths (path_provider). 2. Define a Model Class: Represent database data in a structured way. Helps in mapping data between SQLite rows and Dart objects. 3. pen the Database: Use openDatabase() and getDatabasePath(). Required to establish a connection to the database file. 4. Create a Table Define schema for storing data. Essential for organizing and accessing data efficiently. Example: Book Model Class Inserting Data into SQLite - Convert objects into a map. - Use insert() method: Retrieving Data - Query database and convert results: Updating Data - Use update() method: to modify existing data in the database. Deleting Data - Use delete() method: Complete SQLite Integration Example - Combine all steps in a Flutter project: - Define model. - Set up database connection. - Perform CRUD operations (Create, Read, Update, Delete). - Link database to the UI. Firebase Database Best for applications requiring real-time data synchronization and scalability. Integrates seamlessly with other Firebase services such as authentication and analytics. Ideal for collaborative tools and apps needing cloud-based updates Conclusion Comparison with SQLite: Firebase excels in real-time, cloud-hosted, and multi-user environments. Flutter supports powerful database solutions for both local and cloud storage. SQLite is more suitable for individual, device-local storage requirements. Mobile Application Development Lec. 8 Dr. Samah Adel Flutter Animation Why Use Animations? Animations provide visual feedback and help in making user interfaces more engaging. They can enhance user experience by making transitions smooth, guiding users, and providing context. Types of Animations in Flutter 1. Implicit Animations: Easy-to-use and declarative. Automatically animate properties when they change. Examples:  AnimatedContainer: Changes size, color, or shape.  AnimatedOpacity: Animates opacity changes.  AnimatedPositioned: Changes position of widgets in a Stack. 2. Explicit Animations: Requires more control over the animation, allowing you to define the animation’s behavior. Examples:  AnimationController: Controls the duration, starting point, and progress.  Tween: Defines the start and end values of the animation. Implicit Animations (Examples) AnimatedContainer Example: AnimatedOpacity Example: AnimatedContainer( duration: AnimatedOpacity( opacity: _isVisible ? 1.0 : Duration(seconds: 2), width: _isLarge ? 200.0 0.0, duration: Duration(seconds: 1), child: : 100.0, height: _isLarge ? 200.0 : 100.0, YourWidget(),) color: _isLarge ? Colors.blue : Colors.red,) Explicit Animations (Examples) AnimationController and Tween Example: AnimationController _controller; Tween _tween = Tween(begin: 0.0, end: 200.0); @override void initState() { super.initState(); _controller = AnimationController( duration: Duration(seconds: 2), vsync: this, ); _controller.forward(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, child) { return Container( height: _tween.evaluate(_controller), width: _tween.evaluate(_controller), ); }, ); } Now, we are going to see how we can create explicit animation in Flutter. There are mainly three pillars of an animation, which are given below: 1.Ticker 2.Animation Class 3.AnimationController 1. Ticker The Ticker is a class which sends a signal at a regular interval, i.e., around 60 times per second. You can understand it with your watch, which tics at regular intervals. At each tick, Ticker provides a callback method with the duration since the first ticks at each second, after it was started. Even if the tickers started at different times, it always synchronized automatically. The reason behind this is that the tickers give their elapsed time relative to the first tick after it was started. 2. Animation The Animation class is the core building block of the animation system. The animation is nothing else, but it represents a value (specific type) that can change over the lifetime of an animation. In Flutter, the widgets which perform an animation take an animation object as a parameter. This Animation object gives the information from which they read the current value of the animation and to which they listen for changes to that value. The animation class contains two methods addListener() and addStatusListener(). When the value of animation changes, it notifies all the listeners added with addListener(). Again, when the status of the animation changes, it notifies all the listeners added with addStatusListener(). The most common Animation classes are: Animation: It interpolates values between two decimal numbers over a certain duration. Animation: It interpolates colors between two color values. Animation: It interpolates sizes between two size values. 3. Animation Controller The animation controller is a class that allows us to control the animation. It always generates new values whenever the application is ready for a new frame. For example, it gives the controlling of start, stop, forward, or repeat of the animation. Once the animation controller is created, we can start building other animation based on it, such as reverse animation and curved animation. animcontroller = AnimationController(vsync: this, duration: Duration(milliseconds: 2500)); Here, the duration option controls the duration of the animation process, and vsync option is used to optimize the resource used in the animation. Creating an Animation Step-by-Step 1. Create an AnimationController: Controls the duration and progress of the animation. Example: AnimationController(controller, duration: Duration(seconds: 2)) Example: 2. Define a Tween: AnimatedBuilder( animation: _controller, builder: (context, child) { return Specify the start and end values. Transform.translate( offset: Offset(0.0, _controller.value * 100), child: child, ); }, Example: Tween(begin: 0.0, end: 1.0) child: YourWidget(),); 3. Use AnimatedBuilder: Rebuilds the widget as the animation progresses. Hero Animations What Are Hero Animations?  Hero animations allow a widget to seamlessly transition between screens.  The widget animates from one screen to another, providing visual continuity. Example Usage: Hero( tag: 'hero-tag', child: Image.asset('assets/image.png'), ) When navigating from one screen to another, the widget with the matching tag animates smoothly. Staggered Animations What Are Staggered Animations? Staggered animations allow for a sequence of animations with different start times. Example: final AnimationController controller = AnimationController( vsync: this, duration: Duration(seconds: 3), ); final Tween tween = Tween(begin: 0.0, end: 100.0); final Animation animation = tween.animate(controller); @override void initState() { super.initState(); controller.forward(); } Use multiple controllers with different durations to stagger animations for various widgets. Common Pitfalls and Best Practices Pitfalls to Avoid:  Overusing heavy animations that can cause jank (lag).  Not optimizing the widget tree leading to unnecessary rebuilds. Best Practices:  Use AnimatedContainer, AnimatedOpacity, and AnimatedPositioned for simpler animations.  Use AnimationController and Tween for more custom and complex animations.  Avoid blocking the UI thread by using asynchronous tasks. Performance Considerations Efficient Animations: Keep animations lightweight to ensure smooth performance. Use const constructors when possible to reduce widget rebuilds. Tips: Avoid complex animations on the main thread. Use Flutter DevTools to monitor performance. Understanding Key Components AnimationController: Controls the animation's duration, direction, and state. The controller uses a vsync (a TickerProvider) to ensure efficient animations. Tween: Defines the start and end values for animations (e.g., from 0 to 1, from red to blue). A Tween can be applied to properties like size, color, and position. Animation: Represents the value of the animation as it progresses over time. Animation, Animation, etc., store the current value during the animation. Curves: Define the rate of change over time (e.g., Curves.easeInOut or Curves.linear). Mobile Application Development Lec. 7 Dr. Samah Adel Exploring Flutter Outlines 1. Layouts 2. Gestures 3. State Management Flutter Layouts The main concept of the layout mechanism is the widget. Example The visual layout of the previous image shows a row of three columns, The below image shows three and these columns contain an icon icons with a label under each and label. one. Layout a widget The following steps show how to layout a widget: Step 1: First, you need to select a Layout widget. Step 2: Next, create a visible widget. Step 3: Then, add the visible widget to the layout widget. Step 4: Finally, add the layout widget to the page where you want to display. Types of Layout Widgets We can categories the layout widget into two types: 1.Single Child Widget 2.Multiple Child Widget 1. Single Child Widgets It have only one child widget inside the parent layout widget. These widgets can also contain special layout functionality. The list of different types of single child widgets are: Container: It is the most popular layout widget that provides customizable options for painting, positioning, and sizing of widgets. Center( child: Container( margin: const EdgeInsets.all(15.0), color: Colors.blue, width: 42.0, height: 42.0, ), ) Padding: It is a widget that is used to arrange its child widget by the given padding. It contains EdgeInsets and EdgeInsets.fromLTRB for the desired side where you want to provide padding. const Greetings( child: Padding( padding: EdgeInsets.all(14.0), child: Text('Hello JavaTpoint!'), ), ) Center: This widget allows you to center the child widget within itself. Align: It is a widget, which aligns its child widget within itself and sizes it based on the child's size. It provides more control to place the child widget in the exact position where you need it. SizedBox: This widget allows you to give the specified size to the child widget through all screens. SizedBox( width: 300.0, height: 450.0, child: const Card(child: Text('Hello JavaTpoint!')), ) AspectRatio: This widget allows you to keep the size of the child widget to a specified aspect ratio. AspectRatio( aspectRatio: 5/3, child: Container( color: Colors.bluel, ),), Baseline: This widget shifts the child widget according to the child's baseline. child: Baseline( baseline: 30.0, baselineType: TextBaseline.alphabetic, child: Container( height: 60, width: 50, color: Colors.blue, ), ) ConstrainedBox: It is a widget that allows you to force the additional constraints on its child widget. It means you can force the child widget to have a specific constraint without changing the properties of the child widget. ConstrainedBox( constraints: new BoxConstraints( minHeight: 150.0, minWidth: 150.0, maxHeight: 300.0, maxWidth: 300.0, ), child: new DecoratedBox( decoration: new BoxDecoration(color: Colors.red), ),), CustomSingleChildLayout: It is a widget, which defers from the import 'package:flutter/material.dart'; void main() => runApp(MyApp()); layout of the single child to a class MyApp extends StatelessWidget { // It is the root widget of your application. delegate. The delegate decides @override Widget build(BuildContext context) { to position the child widget and return MaterialApp( title: 'Multiple Layout Widget', debugShowCheckedModeBanner: false, also used to determine the size theme: ThemeData( // This is the theme of your application. of the parent widget. primarySwatch: Colors.green, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget FittedBox: It scales and { @override positions the child widget Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("FittedBox Wi according to the specified fit. dget")), body: Center( child: FittedBox(child: Row( children: [ Container( child: Image.asset('assets/computer. png'), ), Container( child: Text("This is a widget"), ) ], ), fit: BoxFit.contain, ) ), ); } } FractionallySizedBox: It is a widget that Exampel import 'package:flutter/material.dart'; allows to sizes of its child widget according void main() => runApp(MyApp()); to the fraction of the available space. class MyApp extends StatelessWidget { // It is the root widget of your application. @override IntrinsicHeight and IntrinsicWidth: They are Widget build(BuildContext context) { return MaterialApp( a widget that allows us to sizes its child title: 'Single Layout Widget', widget to the child's intrinsic height and debugShowCheckedModeBanner: false, theme: ThemeData( width. // This is the theme of your application. primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } LimitedBox: This widget allows us to limits class MyHomePage extends StatelessWidget { its size only when it is unconstrained. @override Widget build(BuildContext context) { return Scaffold( Offstage: It is used to measure the appBar: AppBar( title: Text("OverflowBox Widget"), ), dimensions of a widget without bringing it body: Center( on to the screen. child: Container( height: 50.0, width: 50.0, OverflowBox: It is a widget, which allows color: Colors.red, child: OverflowBox( for imposing different constraints on its minHeight: 70.0, child widget than it gets from a parent. In minWidth: 70.0, child: Container( other words, it allows the child to overflow height: 50.0, width: 50.0, the parent widget. color: Colors.blue, ), ), ), ), ); } } 2. Multiple Child widgets The multiple child widgets are a type of widget, which contains more than one child widget, and the layout of these widgets are unique. For example, Row widget laying out of its child widget in a horizontal direction, and Column widget laying out of its child widget in a vertical direction. If we combine the Row and Column widget, then it can build any level of the complex widget. Types of multiple child widgets: Example Row: It allows to arrange its import 'package:flutter/material.dart'; void main() => runApp(MyApp()); child widgets in a horizontal class MyApp extends StatelessWidget { // It is the root widget of your application. @override direction. Widget build(BuildContext context) { return MaterialApp( title: 'Multiple Layout Widget', Column: It allows to arrange debugShowCheckedModeBanner: false, theme: ThemeData( its child widgets in a vertical // This is the theme of your application. primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } direction. class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { ListView: It is the most return Center( child: Container( popular scrolling widget that alignment: Alignment.center, color: Colors.white, child: Row( allows us to arrange its child children: [ Expanded( widgets one after another in child: Text('Peter', textAlign: TextAlign.center), ), Expanded( scroll direction. ), child: Text('John', textAlign: TextAlign.center ), Expanded( child: FittedBox( fit: BoxFit.contain, // otherwise the logo will be tiny child: const FlutterLogo(), ), ), ], ), ), ); } } GridView: It allows us to arrange its child widgets as a scrollable, 2D array of widgets. It consists of a repeated pattern of cells arrayed in a horizontal and vertical layout. Expanded: It allows to make the children of a Row and Column widget to occupy the maximum possible area. Table: It is a widget that allows us to arrange its children in a table based widget. Flow: It allows us to implements the flow-based widget. Stack: It is an essential widget, which is mainly used for overlapping several children widgets. It allows you to put up the multiple layers onto the screen. The following example helps to understand it. Building Complex Layout You can create a complex user interface using both single and multiple child layout widgets. The layout framework allows you to create a complex user interface layout by nesting the rows and columns inside of rows and columns. An example of a complex user interface by creating the product list. Flutter Gestures Gestures are an interesting feature in Flutter that allows us to interact with the mobile app (or any touch-based device). Generally, gestures define any physical action or movement of a user in the intention of specific control of the mobile device. Some of the examples of gestures are:  When the mobile screen is locked, you slide your finger across the screen to unlock it.  Tapping a button on your mobile screen.  Tapping and holding an app icon on a touch-based device to drag it across screens. We use all these gestures in everyday life to interact with your phone or touch-based device. Flutter divides the gesture system into two different layers, which are given below: 1.Pointers 2.Gestures 1. Pointers Pointers are the first layer that represents the raw data about user interaction. It has events, which describe the location and movement of pointers such as touches, mice, and style across the screens. Flutter provides a Listener widget to listen to the pointer-events directly from the widgets layer. The pointer-events are categories into mainly four types: 1. PointerDownEvents: It allows the pointer to contact the screen at a particular location. 2. PointerMoveEvents: It allows the pointer to move from one location to another location on the screen. 3. PointerUpEvents: It allows the pointer to stop contacting the screen. 4. PointerCancelEvents: This event is sent when the pointer interaction is canceled. 2. Gestures It is the second layer that represents semantic actions such as tap, drag, and scale, which are recognized from multiple individual pointer events. It is also able to dispatch multiple events corresponding to gesture lifecycle like drag start, drag update, and drag end. Some of the popularly used gesture are listed below: Tap: It means touching the surface of the screen from the fingertip for a short time and then releasing them. This gesture contains the following events: onTapDown onTapUp onTap onTapCancel Double Tap: It is similar to a Tap gesture, but you need to tapping twice in a short time. This gesture contains the following events: onDoubleTap Drag: It allows us to touch the surface of the screen with a fingertip and move it from one location to another location and then releasing them. Flutter categories the drag into two types: 1.Horizontal Drag: This gesture allows the pointer to move in a horizontal direction. It contains the following events: 1. onHorizontalDragStart 2. onHorizontalDragUpdate 3. onHorizontalDragEnd 2.Vertical Drag: This gesture allows the pointer to move in a vertical direction. It contains the following events: 1. onVerticalDragStart 2. onVerticalDragStart 3. onVerticalDragStart Long Press: It means touching the surface of the screen at a particular location for a long time. This gesture contains the following events: onLongPress Pan: It means touching the surface of the screen with a fingertip, which can move in any direction without releasing the fingertip. This gesture contains the following events: onPanStart onPanUpdate onPanEnd Pinch: It means pinching (move one's finger and thumb or bring them together on a touchscreen) the surface of the screen using two fingers to zoom into or out of a screen. Gesture Detector Flutter provides a widget that gives excellent support for all types of gestures by using the GestureDetector widget. The GestureWidget is non-visual widgets, which is primarily used for detecting the user's gesture. The basic idea of the gesture detector is a stateless widget that contains parameters in its constructor for different touch events. Let us learn how we can use these gestures in our application with a simple onTap() event and determine how the GestureDetector processes this. A box widget, design it according to our desired specification, and then add the onTap() function to it. Flutter also provides a set of widgets that can allow you to do a specific as well as advanced gestures. These widgets are given below: Dismissible: It is a type of widget that supports the flick gesture to dismiss the widget. Draggable: It is a type of widget that supports drag gestures to move the widget. LongPressDraggable: It is a type of widget that supports drag gesture to move a widget along with its parent widget. DragTarget: It is a type of widget that can accept any Draggable widget IgnorePointer: It is a type of widget that hides the widget and its children from the gesture detection process. AbsorbPointer: It is a type of widget that stops the gesture detection process itself. Due to this, any overlapping widget cannot able to participate in the gesture detection process, and thus, no event is raised. Scrollable: It is a type of widget that supports scrolling of the content which is available inside the widget. Flutter State Management We know that in Flutter, everything is a widget. The widget can be classified into two categories, one is a Stateless widget, and another is a Stateful widget. The Stateless widget does not have any internal state. It means once it is built, we cannot change or modify it until they are initialized again. On the other hand, a Stateful widget is dynamic and has a state. It means we can modify it easily throughout its lifecycle without reinitialized it again. What is a State? A state is information that can be read when the widget is built and might change or modified over a lifetime of the app. If you want to change your widget, you need to update the state object, which can be done by using the setState() function available for Stateful widgets. The setState() function allows us to set the properties of the state object that triggers a redraw of the UI. The state management categorizes into two conceptual types, which are given below: 1. Ephemeral State 2. App State 1. Ephemeral State This state is also known as UI State or local state. It is a type of state which is related to the specific widget, or you can say that it is a state that contains in a single widget. In this kind of state, you do not need to use state management techniques. 2. App State It is different from the ephemeral state. It is a type of state that we want to share across various parts of our app and want to keep between user sessions. Thus, this type of state can be used globally. Sometimes it is also known as application state or shared state. Some of the examples of this state are User preferences, Login info, notifications in a social networking app, the shopping cart in an e- commerce app, read/unread state of articles in a news app, etc. The following diagram explains the difference between the ephemeral state and the app state more appropriately. The simplest example of app state management can be learned by using the provider package. 1.ChangeNotifier 2.ChangeNotifierProvider 3.Consumer Mobile Application Development Lec. 6 Dr. Samah Adel Flutter – Widgets Whenever you are going to code for building anything in Flutter, it will be inside a widget. The central purpose is to build the app out of widgets. It describes how your app view should look like with their current configuration and state. When you made any alteration in the code, the widget rebuilds its description by calculating the difference of previous and current widget to determine the minimal changes for rendering in UI of the app. The following image is a simple visual representation of the widget tree. Creating Flutter widget Example: Hello World Types of Widget We can split the Flutter widget into two categories: 1.Visible (Output and Input) 2.Invisible (Layout and Control) Visible widget: The visible widgets are related to the user input and output data. Some of the important types of this widget are Text, Button, and Image. Invisible widget: The invisible widgets are related to the layout and control of widgets. It provides controlling how the widgets actually behave and how they will look onto the screen. Some of the important types of these widgets are Column, Row, Center, Padding, Scaffold, and Stack. Visible widget: 1. Text A Text widget holds some text to display on the screen. We can align the text widget by using textAlign property, and style property allow the customization of Text that includes font, font weight, font style, letter spacing, color, and many more. Visible widget: 2.Button This widget allows you to perform some action on click. Flutter does not allow you to use the Button widget directly; instead, it uses a type of buttons like a FlatButton and a RaisedButton. The onPressed property allows us to perform an action when you click the button, and elevation property is used to change how much it stands out. Visible widget: 3.Image This widget holds the image which can fetch it from multiple sources like from the asset folder or directly from the URL. It provides many constructors for loading image, which are given below: Image: It is a generic image loader, which is used by ImageProvider. asset: It load image from your project asset folder. file: It loads images from the system folder. memory: It load image from memory. network: It loads images from the network. To add an image in the project, you need first to create an assets folder where you keep your images and then add the below line in pubspec.yaml file. Example Invisible widget: 1. Icon This widget acts as a container for storing the Icon in the Flutter. Invisible widget: 2. Column A column widget is a type of widget that arranges all its children's widgets in a vertical alignment. It provides spacing between the widgets by using the mainAxisAlignment and crossAxisAlignment properties. In these properties, the main axis is the vertical axis, and the cross axis is the horizontal axis. Invisible widget: 3. Row The row widget is similar to the column widget, but it constructs a widget horizontally rather than vertically. Here, the main axis is the horizontal axis, and the cross axis is the vertical axis. Invisible widget: 4. Center This widget is used to center the child widget, which comes inside it. All the previous examples contain inside the center widget. Invisible widget: 5. Padding This widget wraps other widgets to give them padding in specified directions. You can also provide padding in all directions. We can understand it from the below example that gives the text widget padding of 6.0 in all directions. Invisible widget: 6. Scaffold This widget provides a framework that allows you to add common material design elements like AppBar, Floating Action Buttons, Drawers, etc. Invisible widget: 7. Stack It is an essential widget, which is mainly used for overlapping a widget, such as a button on a background gradient. State Management Widget In Flutter, there are mainly two types of widget: 1. StatelessWidget 2. StatefulWidget 1. StatefulWidget A StatefulWidget has state information. It contains mainly two classes: the state object and the widget. It is dynamic because it can change the inner data during the widget lifetime. This widget does not have a build() method. It has createState() method, which returns a class that extends the Flutters State Class. The examples of the StatefulWidget are Checkbox, Radio, Slider, InkWell, Form, and TextField. 2. StatelessWidget The StatelessWidget does not have any state information. It remains static throughout its lifecycle. The examples of the StatelessWidget are Text, Row, Column, Container, etc. Mobile Application Development Lec. 5 Dr. Samah Adel Concept of Inheritance In Dart, one class can inherit another class, dart can create a new class from an existing class. Terminology: Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or superclass. Child Class: It is the class that inherits the properties of the other classes. It is also known as a deprived class or subclass. Types of Inheritance Inheritance can be of the following three types − Single − Every class can at the most extend from one parent class. Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance. Multi-level − A class can inherit from another child class. Example 1: Example of Single Inheritance in the dart. Example 2: Example of a program for multilevel inheritance Method Overriding Method overriding : It is achieved by re-defining the same method present in the parent class. This method is helpful when you have to perform different functions for a different child class, so we can simply re-define the content by overriding it. Important Points: 1. A method can be overridden only in the child class, not in the parent class itself. 2. Both the methods defined in the child and the parent class should be the exact copy, from name to argument list except the content present inside the method i.e. it can and can’t be the same. 3. A method declared final or static inside the parent class can’t be overridden by the child class. 4. Constructors of the parent class can’t be inherited, so they can’t be overridden by the child class. Example 1 of simple overriding Example 2: When there is more than one child class. The static Keyword The static keyword can be applied to the data members of a class, (fields and methods). A static variable retains its values till the program finishes execution. Static members are referenced by the class name. The super Keyword The super keyword is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property, or method. The following example illustrates the same. Mobile Application Development Lec. 4 Dr. Samah Adel Functions The function is a set of statements that take inputs, do some specific computation and produces output. Functions are created when certain statements are repeatedly occurring in the program and a function is created to replace them. Functions make it easy to divide the complex program into smaller sub-groups and increase the code reusability of the program. Note function_name: defines the name of the function. return_type: defines the datatype in which output is going to come. return value: defines the value to be returned from the function. How to Call Functions? function_name: defines the name of the function. argument list: is the list of the parameters that the function requires. main() Function The main() function is a predefined method in Dart. It is the most important and mandatory part of any Dart Program. Any Dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user-defined statements, and user- defined functions. Synatx void main() { //main() function body } Different Types of Functions There are four types of functions in Dart: 1.No arguments and no return type 2.With arguments and no return type 3.No arguments and with return type 4.With arguments and with return type Examples 1. No arguments and no return type 2. with arguments and no return void MET() type { myPrice(int price) // Creating function { print("Welcome to Mobile Development Course"); print(price); } } void main() void main() { { // Calling the function print( "costs : "); MET(); myPrice(1000); } } 3. With No arguments and With return 4.With arguments and with return type type int add(int a, int b) { int myPrice() // Creating function { int result = a + b; // returning value result int price = 0; return result; return price; } void main(){ } // Calling the function void main(){ var output = add(10, 20); int Price = myPrice(); // Printing output print("costs : ${Price}/-"); print(output); } } Getters and Setters Functions Getters and Setters allow the program to initialize and retrieve the values of class fields respectively. Getters are defined using the get keyword. Setters defined using the set keyword. A getter has no parameters and has a return value, A setter has one parameter and no return value. Syntax: Return_type get identifier set identifier (data type argument) { { // statements // statements return (value) } } Example Symbol => Used in a few different contexts, primarily for concise function syntax and for returning values from functions. 1. Arrow Function: It allows you to define a function in a more concise way, especially for functions that contain a single expression. Example: int add(int a, int b) => a + b; 2. Getter: You can use => in a getter to return a single expression. Example: class Rectangle { final double width; final double height; Rectangle(this.width, this.height); double get area => width * height; } 3. Single Expression Main: In Dart, you can use an arrow function as the entry point for your application. Example: void main() => print('Hello, Dart!'); Object-Oriented Programming(OOP) Dart is an object-oriented programming language, so it supports the concept of class, object … etc. In Dart, we can define classes and objects of our own. We use the class keyword to do so. Dart supports object-oriented programming features like classes and interfaces. Class It is the blueprint of objects and class is the collection of data members and data function means which include these fields, getter and setter, and constructor and functions. Syntax class class_name { } Class is the keyword used to initialize the class. class_name is the name of the class. Fields is A field is any variable declared in a class. Fields represent data about objects. Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. Constructors is responsible for allocating memory for the objects of the class. Functions is Functions represent actions an object can take. They are also at times referred to as methods. Example: Declaring a class class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } Creating Instance of the class To create an instance of the class, use the new keyword followed by the class name. Syntax: var object_name = new class_name([ arguments ]); Example: var obj = new Car("Engine 1") Accessing Attributes and Functions A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. Syntax: Example: //accessing an attribute obj.field_name //accessing a function obj.function_name() Constructors A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you. Syntax Class_name(parameter_list) { //constructor body } Example The this Keyword The this keyword refers to the current instance of the class. Mobile Application Development Lec. 3 Dr. Samah Adel Control Flow in Dart Control Flow in Programming is refers to the order in which set of instructions or statements that are executed or evaluated. It provides flexibility in Decision making and makes code more user friendly. Dart – If-Else Statements ◦ Dart – Switch Case Statements ◦ Dart – Loops ◦ Dart – Loop Control Statements ◦ Labels in Dart ◦ If-Else Statements There are four ways to achieve this: 1. if Statement 2. if-else Statement 3. else-if Ladder 4. Nested if Statement 1. if Statement 2. if-else Statement 3. else-if Ladder 4. Nested if Statement Example Try code of if-else with Operator Switch Case in Dart In Dart, switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java. Syntax Rules to follow in switch case: 1.There can be any number of cases. But values should not be repeated. 2.The case statements can include only constants. It should not be a variable or an expression. 3.There should be a flow control i.e break within cases. If it is omitted than it will show error. 4.The default case is optional. 5.Nested switch is also there thus you can have switch inside switch. Example 1: Normal switch-case statement Example 2: Nested switch-case statement Dart – Loops A looping statement in Dart or any other programming language is used to repeat a particular set of commands until certain conditions are not completed. There are different ways to do so. They are: ◦ for loop ◦ for… in loop ◦ for each loop ◦ while loop ◦ do-while loop 1. for loop For loop in Dart is similar to that in Java and also the flow of execution is the same as that in Java. Syntax: 2. for…in loop For…in loop in Dart takes an expression or object as an iterator. It is similar to that in Java and its execution flow is also the same as that in Java. Syntax: 3. for each … loop The for-each loop iterates over all elements in some container/collectible and passes the elements to some specific function. Syntax: while loop The body of the loop will run until and unless the condition is true. Syntax do..while loop The body of the loop will be executed first and then the condition is tested. Loop Control Statements (Break and Continue) Example 1: Using break inside while loop Example 2: Using break inside do..while loop Example 3: Using break inside for loop Continue Statement: While the break is used to end the flow of control, continue on the other hand is used to continue the flow of control. When a continue statement is encountered in a loop it doesn’t terminate the loop but rather jump the flow to next iteration. Example 1: Using continue inside while loop Example 2: Using continue inside do..while loop Example 3: Using continue inside for loop Mobile Application Development Lec. 2 Dr. Samah Adel Outlines  Why Use Dart  Features of Dart Programming Language  Dart – Hello World Program  Dart – Comments  Dart – Variables  Dart – Operators  Dart – Standard Input Output  Data Types in Dart Why Use Dart Dart is an open-source general-purpose programming language developed by Google. It supports application development on both the client and server side. However, it is widely used for the development of Android apps, iOS apps, IoT(Internet of Things), and web applications using the Flutter Framework. 1. Fast & Smooth: Dart compiles to native code for speedy performance, ideal for mobile apps. 2. Easy to Learn: Similar to familiar languages like Java or Javascript, making it approachable for new developers. 3. Flutter Power: Dart is the heart of Flutter, a popular framework for building beautiful and functional mobile apps. 4. One Code, Many Places: Develop for mobile, web, and even desktop with a single codebase (primarily with Flutter). Features of Dart Programming Language 1. Easy to Understand: as it provides the code Reuse it makes the Programs clean and easy to understand. 2. Object Oriented Programming: Nowadays OOPS is considered as one of the most important feature for many Programming Language including Java and C++. Now, Dart which is following the same path of OOPS. 3. Open Source: Dart is Open Source which makes it quite popular between the Indivisual and also for few big Organisations. 4. Browser Support: Dart Supported by all the browser because of its dart2js compiler that converts dart Program into JavaScript code which can be further processed by all the modern web browsers. 5. Type Safe: Dart is considered as type safe as it is the combination of static and runtime checks to ensure the variable value matches the variable type. 6. Flexible Compilation and Execution: Dart Compilation is flexible as it supports both JIT(Just-in-Time) compilation as well as AOT(Ahead of Time) compilation. And dart2js adds extra value to it. 7. Asynchronous Programming: Dart Supports Asynchronous Programming is where even when a Primary set of tasks are running , Program will respond to other set of tasks and at the end of the execution a final result will be returned. Hello World Program In dart main() function is a predefined method and acts as the entry point to the application. A dart script needs the main() method for execution of the code. The program code goes like this: main(): it is the symbol of main function that means the data entered in it is directly executed by compiler. print(“Hello World!”) : the role of print function is quite simple it just prints the data during the compilation of a program. Comments Types of Dart Comments: 1.Dart Single line Comment. 2.Dart Multiline Comment. 3.Dart Documentation Comment. Variables Types of Variables 1.Static Variable 2.Dynamic Variable 3.Final or const Dynamic Type Variable in Dart This is a special variable initialized with keyword dynamic. The variable declared with this data type can implicitly store any value while running the program. It is quite similar to var datatype in Dart, but the difference between them is the moment you assign the data to a variable with the var keyword it is replaced with the appropriate data type. Note: If we use var instead of dynamic in the above code then it will show error. Final And Const Keyword in Dart These keywords are used to define constant variable in Dart i.e. once a variable is defined using these keyword then its value can’t be changed in the entire code. These keyword can be used with or without data type name. 1. Final A final variable can only be set once and it is initialized when accessed. 2. Const A constant variable is a compile-time constant and its value must be known before the program runs. Null Safety in Dart In Dart, by default a variable can’t be assigned Null value till it is defined that the variable can store Null value in it. This to avoid cases where user assign null value in Dart. To declare a variable as nullable, you append a ‘?' to the type of the variable. The declared variable will by default store null as value and even after assigning it values of your choice you can declare it as null afterwards. Operators Different types of operators in Dart 1. Arithmetic Operators 2. Relational Operators 3. Type Test Operators 4. Bitwise Operators 5. Assignment Operators 6. Logical Operators 7. Conditional Operators Arithmetic Operators Relational Operators Type Test Operators Bitwise Operators Assignment Operators Logical Operators Conditional Operators Standard Input Output Input In Dart programming language, you can take standard input from the user through the console via the use of.readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart. Standard Input Output Output In dart, there are two ways to display output in the console: 1.Using print statement. 2.Using stdout.write() statement. Example Data Types in Dart The data type classification is as given below: 1. Number The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as: int: data type is used to represent whole numbers (64-bit Max). double: data type is used to represent 64-bit precise floating- point numbers. num: type is an inherited data type of the int and double types. 2. Strings in Dart A Dart string is a sequence of UTF-16 code units. With the same rule as that of Python, you can use either single or double quotes to create a string. The string starts with the datatype 3. Boolean It represents Boolean values true and false. The keyword bool is used to represent a Boolean literal in DART. 4. List List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. Declaration of List There are multiple methods to declare List in Dart as mentioned below: 1. Variable Size List 2. Fixed Size List Fixed Size doesn’t mean that we can’t change the size of List, but we have predefined that the List has this much elements while declaring Example 5. Map The Map object is a key and value pair. Keys and values on a map may be of any type. It is a dynamic collection. While Declaring Map there can be only two cases one where declared Map is empty and another where declared Map contains elements in it. Both Cases are mentioned below: Example Mobile Application Development Lec. 1 Dr. Samah Adel WHAT IS FLUTTER? Flutter is an open-source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase. 2 Why Flutter ? Key Features of Flutter 1. CROSS PLATFORM LANGUAGE iOS Android Web Windows Mac OS Linux Embedded Used to build natively compiled applications for mobile, web, and desktop from a single codebase....from a single codebase 5 2. Fast Flutter code compiles to ARM or Intel machine code as well as JavaScript, for fast performance on any device. 6 3. Flexible Control every pixel to create customized, adaptive designs that look and feel great on any screen. 7 4. Beautiful No compromises for your designers 8 5. Productive Build and iterate quickly with Hot Reload. Update code and see changes almost instantly, without losing state. 9 6. Open Everything is free and open source 10 Portable Same code, runs everywhere 9/3/20XX PRESENTATION TITLE 11 Build Flutter anywhere Flutter is supported across tools and platforms we already use + 1,000s of 3rd Party plugins and libraries making the possibilities endless 12 12 From startups to enterprise solutions Over 200,000 Flutter apps 9/3/20XX PRESENTATION TITLE 13 Flutter @ Google Many Google apps were built using Flutter 14 Hello World class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: true, home: Scaffold( body: Center( child: Text('Hello, World!'), ), ), ); } } 15 Structure of Flutter app Material App Scaffold Center Text 16 WHAT IS DART? Coding language used with Flutter framework Dart is a client-optimized language for fast apps on any platform 17 What is Dart? Dart is a programming language designed for client development, such as for the web and mobile apps. It is developed by Google and can also be used to build server and desktop applications. Dart is an object-oriented, class- based, garbage-collected language with C-style syntax 18 9/3/20XX PRESENTATION TITLE 19 https://dart.dev/ Benefits of Dart Optimized for UI Productive development Fast on all platforms Develop with a programming language Make changes iteratively: use hot reload to Compile to ARM & x64 machine specialized around the needs of user see the result instantly in your running app code for mobile, desktop, and interface creation backend. Or compile to JavaScript for the web Hello World void main() { print('Hello, World!'); } 21 Thank you 22

Use Quizgecko on...
Browser
Browser