Dart Programming PPT Insights-Imam Abdulrahman Bin Faisal University .

Dart Programming Jenny Fisher, Yiming Liang, Tianheng Wu, Wen Liu What is Dart? ● Dart is a client-optimized language for developing fast apps on any platform. Why Dart? ● Free and Open Source. ● Optimized for UI. ● Support Productive Development. ● Fast on All Platforms. Data Types Number int, double, num represent numeric literals Strings String Booleans bool represent Boolean values true and false Lists List an ordered group of objects Maps Map represent a sequence of characters represents a set of values as key-value pairs Data Types Scopes ● Lexical Scope language ● The scope of variable is determined statically, simply by the layout of the code. You can “follow the curly braces outwards” to see if a variable is in scope Support to OO Programming Dart is an OOP language Dart has three characteristics in OOP: Encapsulation, inheritance and polymorphism Support to OO Programming Encapsulation 1. methods or attributes are encapsulated in a class this.name=”Yiming” Default constructor : the same name as the class, when class is instantiated, the constructor will be automatically called. this.age=20 Support to OO Programming Encapsulation 2.methods or attributes in a class can be private, so they can not be called by another dart file. Attributes and methods can be private by adding a underscore at the beginning of their name num age; //public attribute num _age; //private attribute run(); //public method _run() //private method Support to OO Programming Encapsulation Num _age //private attribute _run() //private method main function, a new dart file not contains Person. Object p can call attribute name and method printinfo() But p cannot call attribute _age or method _run() (the red warning line under them) Support to OO Programming Inheritance 1. Parent class can inherit any public methods or attributes to their subclass. 2. Like Java, Dart can use “extends” keyword to let subclass get inherited from its parent class. 3. Subclass can both add its methods or attributes and modify methods from its parent class (by using @override) 4. However,Parent class cannot inherit its constructor, private methods or attributes to their subclass. Web: subclass Person: parent class Object w can call the method run() ,personinfo() and work() from Web rather than Person. Using “super” keyword can call method from parent class. super.work() (call Person method work()) Support to OO Programming polymorphism A parent class, which defines virtual method and attribute(abstract class) ,its subclass must implement all of methods and attribute from the parent class and override them. Also the parent class cannot be instantiated. The printer(parent class, abstract class) music(), printing() and receiving() are virtual methods ,var uri is a virtual attribute Receiving a phone call (subclass phonecall implements the abstract class printer, only receiving a phonecall (a function)) t constructor printing Play music Main function(instantiate three classes) result Implement three functions The printer can playmusic, printpaper and phonecall (multifunction) Functional Programming Pass a function as a parameter to another function. Functional Programming Assign a function to a variable. Create an anonymous function that can be assigned to a variable. Functional Programming Currying. Shorthand syntax Equal to Calling add(a) like this will return a function, which is (b) ⇒ a + b;. Exception Handling and Event Handling Exceptions Throw and catch exceptions. Exception Handling and Event Handling Throw Throwing is an expression, thus can be used in ⇒ statements and anywhere else that allows expressions. Exception Handling and Event Handling Catch Use on to capture a certain type of exception. Use catch to capture the exception object. Use rethrow to throw captured exception. Use the second parameter, the stack trace, to get information about the call sequence that triggered an exception. Exception Handling and Event Handling Finally Expressions run with or without an exception thrown. Concurrency Concurrent programming using isolates: independent workers that are similar to threads but don’t share memory, communicating only via messages. To use this library in your code: import ‘dart:isolate’; https://api.dart.dev/stable/2.14.2/dart-isolate/dart-isolate-library.html Isolate ● The definition of isolate ○ ○ ○ ○ implementation of the Actor concurrency mode. a running entity with its own memory and single-threaded control. The code in isolate is executed in sequence, and the concurrency of any Dart program is the result of running multiple isolates. isolate has no shared memory, there is no possibility of contention, so no locks are needed, and there is no need to worry about deadlocks. ● Communication between isolates ○ through ReceivePort and SendPort, and message delivery in Dart is always asynchronous libraries ● Libraries in Dart are modules with specific functions: ○ contain a single file or multiple files ○ library can be divided into three categories:Custom library,System library, public library ● Declare the library through the keyword: library ○ ○ ○ Each Dart file is a library by default, but the library is not used to display the declaration uses identifiers starting with _underscore to indicate that the access in the library is visible (private). The suggestion of name of a library: lowercase characters + _ , eg. http_auth Import the library through keyword:import ● Import Different types of libraries in different ways ○ ○ ○ import ‘dir/fileName.dart’; import ‘dart:fileName’; import “package:xxx/xxx.dart” ● Import libraries with some specific function (import on demand): ○ include:show import ‘dir/fileName.dart’ show f1,f2…; ○ exclude:hide import ‘dir/fileName.dart’ hide f1,f2…; ● Specify the prefix of the library (resolve naming conflicts): import ‘dir/fileName.dart’ as name1; ● Lazy loading:import ‘dir/fileName.dart’ deferred as func; ● Assemble the library through keyword: part, part of ● Create library package: https://dart.dev/guides/libraries/create-librarypackages Programming Language:GO Group:12 Shudong Lai, Jingzhou Shen, Jie Zhu Go 🞐 Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. 🞐 Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency. Content 🞐 Names, Binding, and Scopes 🞐 Concurrency 🞐 Data Types 🞐 Expressions and Assignment Statements 🞐 Exception Handling and Event Handling 🞐 Functional Programming 🞐 Support to OO programming Names, Binding, and Scopes 🞐 A variables name can use letters, numbers and underline(“_”). But first character must be letters or underline. And it is Case sensitive. Reserved Word Names, Binding, and Scopes 🞐 It also has local variables and global variables. Local variables have the first priority. For example: Data Types 🞐 Go has different data types such as boolean, int, float, pointer, array, struct, function, slice, interface and so on. Slice 🞐 An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays. Expressions and Assignment Statements 🞐 Go has the following character represent operators to make the language more convenient and shorter. Warning: the golang cannot allow variables with different data type to operator with each other Expressions and Assignment Statements There are three ways for assignment: 1. Var v1, vtype1 V1 = value //If not initialize it, the value would be 0 2. Var v1 = value //The type of the v1 would depend on the data type of the value 3. V1 := value //Identify and initialize the variable //This method cannot be used if the variable has already been declared OO programming: Struct 🞐 Go supports OOP. 1. It doesn’t have “class”, but it supports struct, like: type Creature struct { Name string Real bool } Structs are user-defined types. Struct types (inclu
ding methods) provide services similar to classes in other languages. 2. You can embed anonymous structs into each other, like: type FlyingCreature struct { Creature WingSpan int } And at that time you can do things like that: dragon := &FlyingCreature{ Creature{“Dragon”, false }, 15, } OO programming: Interface 🞐 Interfaces are a hallmark of the Go language’s object-oriented support. An interface is a type that declares a set of methods. Like interfaces in other languages, they do not contain implementations of methods. 🞐 Objects that implement all interface methods automatically implement the interface. It has no inheritance or subclass or “implements” keyword. Concurrency 🞐 Goroutine is at the heart of Go’s parallel design. A Goroutine is essentially a coroutine, but it’s smaller than a thread. It’s not strictly a thread, They are not true threads because they do not always execute in parallel. However, because of multiplexing and synchronization, you get concurrent effects. Just like the example below: It will generate a random series of “world”, ”hello”. Concurrency: Channels 🞐 Channels are a typed conduit through which you can send and receive values with the channel operator, val sex = “male” sex: String = male · Block expression In Scala, {} is used to represent a block expression Loop · for for(i val nums = 1.to(10) nums: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //print for loop scala> for(i var i = 1 i: Int = 1 scala> while(i do something; if case failure -> do something. //An example of how this works def trySuccessFailure(a: Int, b: Int): Try[Int] = Try { Calculator.sum(a,b) } For example: Running out of memory. Thrown by system, never by user programs For example: NullPointerExce ption “trySuccessFailure” should “handle NegativeNumberException” in { import CalculatorExceptions._ val result = trySuccessFailure(-1,-2) result match { case Failure(e) => assert(e.isInstanceOf[NegativeNumberException]) case Success(_) => fail(“Should fail!”) }} Event Handling of Scala Codes GUI: ● //define the object Scala uses Java GUI for UI. As a result, the event handling model of it is basically the same. Three steps: 1) Define the UI objects like a button. 2) Listen to the objects. 3) Add reactions while on change of the state (such as onClick() or selectionChanged(..) ). val likeScala = new CheckBox(“I like Scala”) likeScala.selected = true //Listen listenTo(likeScala) //add reactions reactions += { case ButtonClicked(`likeScala`) => if (!likeScala.selected) { if (Dialog.showConfirmation(contents.head, “Are you sure you don’t like Scala?”) != Dialog.Result.Yes) likeScala.selected = true }} Pure Function Definition • • • The function’s output depends only on its input variables It doesn’t mutate any hidden state It doesn’t read data from the outside world (including the console, web services, databases, files, etc.), or write data to the outside world Examples abs ceil max min isEmpty length substring def double(i: Int): Int = i * 2 But impure functions are needed … Write the core of your application using pure functions, and then write an impure “wrapper” around that core to interact with the outside world. If you like food analogies, this is like putting a layer of impure icing on top of a pure cake. Passing Function Around Create functions as variables Example ● val doubles = nums.map(_ * 2) ● def double(i: Int): Int = i * 2 ● val doubles = nums.map(double) ● val double(i: Int): Int => i * 2 Method or Function •The def syntax is more familiar to people coming from a C/Java/C# background •You can use def methods just like they are val functions No Null Values -Use Option Option/Some/None classes Use Option and Some Thank You! SWIFT Zihao Li; Sihan Adi; Sitong Wan; Ziyan Guo BECIK,INC // Presentation Title Goes Here www.companyname.com Names, Binding, and Scopes 1. Names 1) Case sensitive, Myname and myname are two different identifiers; 2) The first character of the identifier can start with an underscore (_) or a letter, but it cannot be a number; 3) Other characters in the identifier can be underscore (_), letters or numbers. 4) Constant and variable names can contain almost any character, including Unicode characters. let 🐶🐮 = “dogcow” BECIK,INC // Presentation Title Goes Here 5) keywords are reserved and can’t be used as identifiers, unless they’re escaped with backticks. let ’class‘ = “Runoob” 2. Binding A binding is an association between an attribute and an entity. If we want to use variables in a programming language, we need to have the ability to associate values with variable names, and to extract the values when needed. Like C, Swift uses variables to store and refer to values by an identifying name. www.companyname.com Names, Binding, and Scopes 3. Scopes func getAge() -> Int { var age = 42 age += 1 return age } var age = 99 var anotherAge = getAge() anotherAge += 1 print(age) print(anotherAge) BECIK,INC // Presentation Title Goes Here We’re working with 2 kinds of scope in this example, the global and local scope. The local scope is present within the function getAge(). The global scope is present everywhere. Variables defined at the highest level of the code, i.e. outside of functions, classes, etc., can be used everywhere. Two essential rules: You cannot use a variable outside the scope it’s declared in. Variable names must be unique within their own scope. www.companyname.com Functional Programming 3. In-Out Parameters 1. Defining functions uses the keyword func, and we can indicate the function’s return type with the return arrow ->. 1) Write an in-out parameter by placing the inout keyword right before a parameter’s type. 2) Place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function. func greet(person: String) -> String { let greeting = “Hello, ” + person + “!” return greeting } 2. Calling function print(greet(person: “Anna”)) // Prints “Hello, Anna!” print(greet(person: “Brian”)) // Prints “Hello, Brian!” BECIK,INC // Presentation Title Goes Here func swap(_ a: inout Int, _ b: inout Int) { let temp1 = a a=b b = temp1 } var x = 1 var y = 5 swap(&x, &y) www.companyname.com Functional Programming 4. Omitting Argument Labels If a parameter has an argument label, the argument must be labeled when you call the function. And if you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter. BECIK,INC // Presentation Title Goes Here 5. Default Parameter Values We can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, we can omit that parameter when calling the function. www.companyname.com Functional Programming 6. Variadic Parameters A variadic parameter accepts zero or more values of a specified type. We use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. BECIK,INC // Presentation Title Goes Here www.companyname.com Swift Data Types Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process. Like other major languages: Int, Float, Double, String, Bool -Boolean, Character Type check var A = 42 A = ”Hello, World” print(A) (The following error will be reported☺) error: cannot assign value of type ‘String’ to type ‘Int’A = “Hello, World” BECIK,INC // Presentation Title Goes Here Type-checking helps you avoid errors when you’re working with different types of values. However, this doesn’t mean that you have to specify the type of every constant and variable that you declare. www.companyname.com 2 Swift Data Types–Type inference It is not necessary to specify the type when declaring constants and variables. If you don’t specify the type of value you need, Swift uses type
inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code simply by examining the values you provide. Type inference For example: In the same way, if you don’t give a floating-point type, Swift will infer that you want a Double: When inferring the type of floating-point numbers, Swift will always choose Double instead of Float. If an integer and a floating-point number appear in the expression at the same time, it will be inferred to be the Double type: BECIK,INC // Presentation Title Goes Here www.companyname.com Expressions and Assignment Statements b = a // now b is equal to a Simple assignment operation, assign the right operand to the left operand. • If the right side of the assignment is a tuple with multiple values,its elements can be decomposed into multiple constants or variables at once For example : var (a, b) = (3, 4) // now a = 3 and b = 4 • BECIK,INC // Presentation Title Goes Here Note 1: The assignment operator in Swift does not return a value by itself.So equal operator is “==”. Note 2: ++, — has been cancelled in swift3 www.companyname.com Expressions and Assignment Statements The half-open interval (a.. multiplication/division => addition/subtraction ► Assignment ► Cannot overload the default assignment operator (=), but compound assignment operator (+=, -=, *=, /=) can be overloaded Expressions and Assignment Statements in Swift ► Precedence Group Declaration: