Professional Documents
Culture Documents
AKSHAYA R
ASSISTANT PROFESSOR
ARTIFICIAL INTELLIGENCE & DATA
SCIENCE
DART OVERVIEW
o In 2013, Dart reached milestone releases and introduced Dartium, a browser with a
built-in Dart VM. Shifting focus, Google introduced Flutter in 2015, using Dart as its
core language for cross-platform app development.
o Dart 2.0 arrived in 2018, enhancing syntax and performance, while strong mode
bolstered type checking.
o Today, Dart's popularity thrives mainly through its integration with Flutter, making it a
favored choice for building modern and visually appealing applications across
platforms.
POPULARITY AND USAGE
▪ Dart gained recognition, especially with the advent of the Flutter framework, which
uses Dart as its primary language.
▪ Flutter, powered by Dart, is a UI toolkit for building natively compiled applications for
mobile, web, and desktop from a single codebase.
▪ Dart's popularity surged as Flutter gained traction for its rapid development,
expressive UI, and cross-platform capabilities.
▪ Dart's usage extends beyond Flutter. It can be employed for web development and
even server-side programming, though its prominence mainly lies in mobile and web
app development.
WHY DART
▪ Efficiency: Dart's focus on performance and concurrency makes it suitable for building
high-performance applications, especially those that require real-time updates or
handling multiple tasks simultaneously.
▪ Productivity: Dart offers a clean and readable syntax, which contributes to developer
productivity. Features like hot-reloading (in Flutter) speed up the development
process.
▪ Cross-Platform Development: With Flutter, Dart allows you to build applications that
work across multiple platforms (iOS, Android, web, desktop) from a single codebase
reducing the development time and effort.
WHY DART
▪ Flutter Ecosystem: Flutter's rich set of widgets and tools for UI development
have gained popularity in the mobile and web development communities.
▪ Being developed by Google, Dart has a strong backing from a tech giant. This
support helps ensure its continued development, improvements, and adoption.
KEY FEATURES OF DART
✔ Strong Typing: Dart employs strong typing, which helps catch type-related errors
early in the development process, enhancing code reliability.
✔ Modern Syntax: a clean and readable syntax. Its structure encourages code
organization and maintainability.
KEY FEATURES OF DART – CONTD.
✔ Hot Reload (Flutter): In conjunction with Flutter, Dart introduces a unique feature
called hot reload, enabling developers to see instant changes in the application as they
modify the code.
It is where the program execution starts and flows to other functions and statements.
import 'dart:io';
void main() {
// Program code
}
VARIABLES
In Dart, variables are used to store and manipulate data. Dart is a statically typed
language, which means that variables have a specific data type associated with them, and
this data type is determined at compile-time.
Variables are declared using the var, final, or const keyword, followed by the variable
name.
final is used for variables that are initialized once and cannot be changed afterward.
You can omit the data type when declaring a variable, and Dart will infer it from the
assigned value.
You can explicitly specify the data type of a variable using the Type followed by the
variable name.
Dynamic Typing:
Dart also supports the dynamic type, which allows a variable to hold values of any
type.
Variables are Lexically Scoped: Variables are only accessible within the scope they
are declared in.
Default Values:
final variables are initialized once at runtime, while const variables are compile-time constants.
var and dynamic variables can be reassigned to values of different types, while final and const
variables cannot be reassigned once initialized.
VARIABLE NAMING CONVENTIONS AND RULES
Naming Conventions:
Variables should have meaningful names that reflect their purpose in the program.
This enhances code readability and understanding.
Use camelCase: Begin with a lowercase letter and capitalize the first letter of
subsequent words (e.g., studentName, totalAmount).
VARIABLE NAMING CONVENTIONS AND RULES –
CONTD.
Naming Rules
4. Variable names are case-sensitive (myVariable and myvariable are considered different).
5. Don't use reserved words (keywords) as variable names (e.g., var, int, double, if, while).
6. Use names that make the purpose of the variable clear, like age, userName, totalAmount.
DART DATA TYPES
'name': 'John',
'age': 30,
};
Runes t = Runes('\u2665’);
To read input:
The method readLineSync() is one of the methods used to take input from
the user.
else if: Executes one block of code if the condition is true, and another if it's false.
Example:
if (condition1) {
} else if (condition2) {
} else {
Example:
// Code to execute
// Code to execute
}
LOOPS
for Loop
The for loop allows you to iterate over a collection of items a specified number
of times or to perform an action based on a specific condition.
print('Value of i: $i');
}
LOOPS
for-in Loop
The for-in loop is used to iterate over elements of an iterable, such as a list, set,
or map.
print('Number: $number');
}
LOOPS
while Loop
The while loop repeatedly executes a block of code as long as a specified condition is
true.
var i = 0;
while (i < 5) {
print('Value of i: $i');
i++;
}
LOOPS
do-while Loop
The do-while loop is similar to a while loop, but it guarantees that the block of code is
executed at least once before checking the condition.
var i = 0;
do {
print('Value of i: $i');
i++;
forEach Loop
Dart provides the `forEach` method to iterate over elements in an iterable like
a list.
fruits.forEach((fruit) {
print('Fruit: $fruit');
});
LOOPS
Iterable Loop
Dart offers several methods for iterating over collections, such as `map`,
`where`, `reduce`, and others. These methods allow you to perform operations
on the elements of a collection.
print(squaredNumbers.toList());
STRINGS
String Declaration:
String Concatenation:
Multiline Strings:
Dart supports multiline strings using triple quotes (''' or """). Multiline strings can span
across multiple lines, preserving line breaks and whitespace.
''';
STRINGS – CONTD.
Escape Characters:
Dart also supports escape characters within strings, allowing you to include
special characters like newline (\n), tab (\t), and more.
String Methods:
String interpolation in Dart is a powerful feature that allows you to embed expressions
and variables directly within a string. This feature helps create dynamic strings by
evaluating the expressions and replacing them with their values. String interpolation is
achieved using the ${expression} syntax within a string.
print(greeting);
You can use string interpolation not only with variables but also with expressions, function calls,
and even complex expressions. Here are some more examples:
int quantity = 5;
String interpolation enhances code readability and reduces the need for manual string
concatenation, making your code cleaner and easier to understand
FUNCTIONS IN DART
Example:
return a + b;
}
FUNCTIONS IN DART
Parameters:
Functions can take zero or more parameters, which are the values passed to the
function when it's called. Parameters have a name and a type.
}
FUNCTIONS IN DART
Optional Parameters:
Dart supports optional parameters using curly braces {} for named parameters and square
brackets [] for positional parameters.
//
//
}
FUNCTIONS IN DART
You can specify default values for parameters, which are used if a value is not provided
when the function is called.
print("Hello, $name!");
Recursive Functions:
Dart allows you to define recursive functions, where a function can call itself.
USING FUNCTIONS AS VARIABLES WITH CLOSURES IN
DART
Functions are treated just like any other data type, such as integers or strings.
This means you can:
This flexibility enables you to write more modular and reusable code.
FUNCTIONS AS VARIABLES
Just like you can store numbers, strings, or other data in variables, you can also
store functions in variables in Dart. This means you can assign a function to a
variable, and that variable can then be used to call the function.
var myFunction = () {
};
Here, myFunction is a variable that holds a function. You can call myFunction to
execute the code inside it.
CLOSURES
✔ Closures are functions that "remember" the environment in which they were
created, including the variables and values that were in scope at that time. This
means that even if you call a closure outside of its original scope, it can still
access and use those remembered variables.
void main() {
int x = 10;
// Create a closure
return x + y;
};
print(result); // Output: 15 }
USING FUNCTIONS AS VARIABLES WITH CLOSURES IN DART -
BENEFITS
Code Reusability: You can reuse closures across different parts of your code
▪ Classes are used to define blueprints for objects, encapsulate data and behavior,
and promote code organization.
class Person {
String name;
int age;
// Constructor
Person(this.name, this.age);
void greet() {
}}
CONSTRUCTOR SHORTHAND IN DART
In Dart, the Class Constructor Shorthand allows you to declare class properties directly
in the constructor parameter list using the this keyword. You do not need to explicitly
declare the class properties and assign them in the constructor's body.
It lets you save time and make your code more concise by eliminating the need
for additional property declarations and assignments in the constructor body.
CONSTRUCTOR SHORTHAND IN DART
class Person {
String name;
int age;
Person(this.name, this.age);
In this example, instead of separately declaring name and age as properties and then assigning
them in the constructor, the shorthand allows you to declare and initialize them directly in the
constructor's parameter list using this keyword. This makes your code cleaner and more
efficient.
CREATING CLASSES AND USING THE CLASS
CONSTRUCTOR SHORTHAND IN DART
Dart provides a simple way to create classes using the class keyword. Here's an example
of a class with a constructor shorthand:
class Person {
String name;
int age;
Collections in Dart:
List: An ordered collection of elements. Lists can contain elements of the same or
different types.
Set: An unordered collection of unique elements. Sets are useful for ensuring
uniqueness and checking membership.
Map: A collection of key-value pairs, where each key maps to a value. Keys are
unique within a map.
GROUPING AND MANIPULATING DATA WITH
COLLECTIONS IN DART – CONTD.
Grouping Data:
Grouping: Categorizing elements based on certain criteria. For instance, grouping a list
of people by age to create age-based categories.
Manipulating Data:
Joining: Combining elements from multiple collections into a single collection. For
example, merging two lists of names.
void main() {
}
In this example,
where method - to filter out the even numbers and store them in the evenNumbers list.
map method - to square each number and store the results in the squaredNumbers list.
reduce method - to calculate the sum of all the numbers and store it in the total variable.
LESS CODE WITH HIGHER ORDER-FUNCTIONS IN DART
In Dart, using higher-order functions can lead to less code while maintaining or
even enhancing the functionality of your programs.
2. Code Abstraction: You can abstract away complex or repetitive code into
higher-order functions. This makes your code more focused on what needs to be done
rather than how it should be done.
Dart's where method is a higher-order function that filters a list based on a given
condition. It abstracts away the need for writing a loop to filter elements.
The map method transforms each element of a list according to a provided function.
It abstracts away the need for writing a loop to iterate and modify elements.
reduce:
You can create your own higher-order functions to abstract away complex tasks.
Consider, a custom higher-order function called repeatFunction as an example. This function will take
another function and an integer n as arguments. It will return a new function that executes the provided
function n times.
return () {
};
}
LESS CODE WITH HIGHER ORDER-FUNCTIONS IN DART
In this repeatFunction,
n - integer argument that specifies the number of times we want to repeat the
function.
The repeatFunction returns a new function that repeats the provided function n
times.
The cascade operator in Dart allows to perform a sequence of operations on the same
object without having to repeat the object's name. It's especially useful when you need
to make multiple method calls or property assignments on an object.
class Person {
int age = 0;
}
CASCADE OPERATOR (..) – CONTD.
void main() {
..name = 'Alice'
..age = 30;
print(person.age); // Output: 30
In this example, Person object is created and its name and age properties are set using the
cascade operator ...
DART NULL SAFETY
Dart Null Safety is a feature introduced in the Dart programming language to help developers
write safer and more reliable code by minimizing null reference errors, which are a common
source of bugs in many programming languages.
Null safety is designed to make it easier to work with null values and to prevent unexpected null
pointer exceptions at runtime.
In Dart Null Safety, all types are categorized as either nullable or non-nullable.
✔ Nullable types are indicated by adding a ? suffix to the type, such as String?, int?, or Object?.
✔ Non-nullable types do not have a ? suffix and are considered to always have a non-null value.
DART NULL SAFETY
Non-nullable by Default:
Dart Null Safety introduces a default non-nullable behavior for variables and fields. This
means that unless you explicitly specify a variable as nullable using the ? suffix, it is
assumed to be non-nullable.
Late Initialization:
Null-aware Operators:
Dart provides operators that allow you to safely work with nullable values without
causing null pointer exceptions.
The null-aware operators include the null conditional operator (?.), the
null-aware cascade operator (..?), and the null coalescing operator (??).
WIDGETS
Widgets are the core elements used to build the UI in Flutter applications.
✔ They are used to describe how the UI should look and behave based on the
application's current state.
▪ You can nest widgets inside other widgets to create complex UI hierarchies.
Structural widgets define how elements are laid out, like Container, Row, Column,
and Stack.
Appearance widgets define the visual characteristics of elements, like Text, Icon,
and Image.
WIDGETS
Flutter distinguishes between two main types of widgets: stateless and stateful.
Stateless Widgets: Stateless widgets are immutable, meaning they do not change their
internal state once they are created. They are used for UI components that remain static
and do not respond to user interactions. For example, displaying a label with static text.
Stateful Widgets: Stateful widgets, on the other hand, can change and update their
state over time. They are used for UI components that need to react to user input or
changes in the application's data. For example, a counter that increments when a button is
pressed..
WIDGETS
Widget Tree:
Widgets are organized in a hierarchical structure called the "widget tree" or "widget
hierarchy." At the top of the tree is typically a root widget like MaterialApp or
CupertinoApp, which sets up the basic structure of your app. Child widgets are then
nested within this root widget, defining the layout and behavior of the UI.
build Method:
All widgets, whether stateless or stateful, have a required build method that must be
implemented. This method defines how the widget should render its content based on
the current state and properties. The build method returns a widget representing the UI.
WIDGETS
Reactive UI:
Widgets in Flutter are reactive, meaning they can rebuild themselves in response
to changes in their properties or the app's state. Stateful widgets, in particular, can
trigger a rebuild of their UI when their internal state changes.
Event Handling:
Custom Widgets:
You can create custom widgets by extending either StatelessWidget or StatefulWidget. Custom
widgets encapsulate parts of your UI and functionality, promoting code modularity and reusability.
State Management:
For managing application state, Flutter provides various options and packages like Provider, Bloc,
and GetX. These help in managing and sharing data across widgets and updating the UI
accordingly.
Flutter provides layout widgets like Container, Row, Column, and styling widgets like TextStyle
and Theme to control the visual appearance and positioning of widgets within the UI.
THANK YOU