Dart Programming Language
Dart is an open-source, general-purpose programming language developed by Google. It is designed to be approachable, portable, and productive, making it suitable for high-quality app development on any platform.
Dart supports both client-side and server-side development and is widely used for building Android, iOS, IoT, and web applications, especially with the Flutter framework
Dart is a strongly typed, object-oriented language with a syntax similar to Java, C, and Javascript.
Dart is statically typed language - meaning a variable type is declared once and will never change
Flutter
Flutter is Google's portable UI Framework for building modern, native, and reactive applications for iOS and Android.
Flutter uses dart to create your user interface, removing the need to use separate languages like Markup or visual designers.
Setting Up Development Environment
Software Requirements:
Git for Windows 2.27 or later
Android Studio 2024.1.1 (Koala) or later
Visual Studio Code 1.86
use the dart create command and the console template to create a command-line app:
$ dart create -t console cli
Run the app
$ dart run
Introduction to Dart
Hello World
Every app requires the top-level main() function, where execution starts.
void main() {
print('Hello, World!');
}
Functions that don't explicitly return a value have the void return type. To display text on the console, you can use the top-level print() function.
Numbers (int, double)
Integer(int, no decimals)
Double (double, decimal number)
Strings (String)
Booleans (bool)
Lists (List, also known as arrays)
Sets (Set)
Maps (Map)
DateTime (A point om time)
Duration (A span of time)
You can declare most variables without explicitly specifying their type using var
Variable types are determined by their initial values:
void main() {
// declaring variables with variables not specifying the type
var name = "Junn";
var height = 5.9;
// declaring variables with variable types declared
String department = "IT Department";
num extNo = 406;
bool isLecturer = false;
//printing variable values
print("Name is $name");
print("Department is $department");
print("Exension No is $extNo");
print("Height is $height");
print("Lecturer Status is $isLecturer");
}
The Dart language enforces sound null safety, meaning this prevents an error that results from unintentional access of variables set to null.
An exception to this rule is when null supports the property or method, like toString() or hashCode. During compile time the Dart compiler detects these potential errors
String? name // Nullable type. Can be `null` or string.
String name // Non-nullable type. Cannot be `null` but can be string.
If you're sure that a variable is set before it's used, but Dart disagrees, you can fix the error by marking the variable as late
late String description;
void main() {
description = 'Feijoada!';
print(description);
}
*If you fail to initialize a late variable, a runtime error occurs when the variable is used.
If you never intend to change a variable, use final or const.
A final variable can be set only once; a const variable is a compile-time constant
Setting final variable
final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';
Changing the value of a final variable will give you an error
✗ static analysis: failure
name = 'Alice'; // Error: a final variable can only be set once.
Example of const variables
var foo = const [];
final bar = const [];
const baz = []; // Equivalent to `const []`
You can't change the value of a const variable
✗ static analysis: failure
baz = [42]; // Error: Constant variables can't be assigned a value.
Example:
2 + 3 == 5
2 - 3 == -1
2 * 3 == 6
5 / 2 == 2.5 //Result is double
5 ~/2 == 2 // Result is an int
5 % 2 == 1 // Remainder
Example:
void main() {
int num1 = 100;
double num2 = 130.2;
num num3 = 50;
num num4 = 50.4;
print(num3 + num4);
}
Rounding Double Value to 2 Decimal Places
The .toStringAsFixed(2) is used to round the double value upto 2 decimal places in dart. You can round to any decimal places by entering numbers like 2, 3, 4, etc.
void main() {
double price = 1130.232546;
print(pirce.toStringAsFixed(2));
}
If you want to create a multi-line String in dart, then you can use triple quotes with either single or double quotation marks
void main() {
String multiLineTextSingle = '''
This is a multiline text.
It is written in Dart programming language.
using three single quotes
''';
print(multiLineTextSingle);
}
void main() {
String multiLineTextDouble = """
This is a multiline text.
It is written in Dart programming language.
using three Double quotes
""";
print(multiLineTextDouble);
}
\n - New Line
\t - Tab
void main() {
String name = "UTAS";
String course = "Mobile Programming";
print("This is using NewLine $name\n $course");
In dart, type conversion allows you to convert one data type to another type. For e.g. to convert String to int, int to String or String to bool, etc.
String to Integer
Convert String to int using int.parse()
void main() {
String Strvalue = "1";
print("Type of strvalue is ${Strvalue.runtimeType}");
int intvalue = int.parse(Strvalue);
// prints the converted value
print("Value of intvalue is $intvalue");
// prints the variable tyoe
print("Type of intvalue is ${intvalue.runtimeType}");
}
String to Double
String to double using double.parse() method
void main() {
String strValue = "1.1";
print("The variable type of strvalue is ${strValue.runtimeType}");
double doubleValue = double.parse(strValue);
print("The value of doubleValue is $doubleValue");
print(
"The variable type of doubleValue is changed to ${doubleValue.runtimeType}");
}
Integer to String
convert int to String using the toString() method
void main() {
int one = 1;
print("The variable one has a type of ${one.runtimeType}");
//convert integer to string
String oneIntToString = one.toString();
print(
"The variable oneIntToString has a type of ${oneIntToString.runtimeType}");
print("The value of oneIntToString is $oneIntToString");
}
double to integer
convert double to int using the toInt() method.
void main() {
double num1 = 10.01;
int num2 = num1.toInt();
print("The value of num1 is $num1. The datatype is ${num1.runtimeType}");
print("The value of num2 is $num2. The datatype is ${num2.runtimeType}");
}
void main() {
final greeting = greet('Junn', 25);
print(greeting);
}
String greet(String name, int age) {
return "Hello $name, you are $age years old";
}
void main() {
String setDate = '2008-07-20';
// Convert String to DateTime
DateTime parseDate = DateTime.parse(setDate);
DateTime dateNow = DateTime.now();
Duration dateDuration = dateNow.difference(parseDate);
print("The parsed setDate value $parseDate");
print("The date today $dateNow");
print("The date Duration difference of date now and setdate $dateDuration");
print("The date in days ${dateDuration.inDays}");
print("The date in Hours ${dateDuration.inHours}");
print("The date in minutes ${dateDuration.inMinutes}");
print("The date in seconds ${dateDuration.inSeconds}");
print("The date in milliseconds ${dateDuration.inMilliseconds}");
print("The date in microseconda ${dateDuration.inMicroseconds}");
}
Note: $variable vs ${variable} when including a variable inside a string you can add the $ or ${} sign. This is called interpolation
using the readLineSync() function
e.g.
// importing dart:io file
import 'dart:io';
void main() {
print("Enter your name?");
// Reading the name from the user
String? name = stdin.readLineSync(); // null safety in name string
// Printing the name
print(
"Hello, $name! \n You have successfully read a value from a user input!!");
}
if statements and elements
Dart supports if statements with optional else clauses.
void main()
{
num status = 0;
if (status == 1)
{
print("Status is 1");
}
else if (status == 2)
{
print("Status is 2");
}
else
{
print("Status is neither 1 nor 2");
}
}
A switch statement evaluates a value expression against a series of cases.
void main()
{
num status = 0;
switch (status)
{
case 1:
print("Status is 1");
break;
case 2:
print("Status is 2");
break;
default:
print("Status is neither 1 nor 2");
}
}
for Loops
void main()
{
for (var i = 0; i < 5; i++) {
print('!');
}
}
while Loops
A while loop evaluates the condition before loop:
void main()
{
bool isContinue = true;
num i = 0;
while (isContinue)
{
print("This is while loop iteration $i");
i++;
if (i == 5)
{
isContinue = false;
}
}
}
do while Loops
A do-while loop evaluates the condition after the loop:
void main(){
num i = 0;
do {
print('This is do-while loop iteration $i');
i++;
} while (i < 5);
}
Find the Greatest Number
Ask the user to input 3 numbers. Using Conditions your program should determine if the first number is greater than the second number, if the third number is greater than the second number and if the first number is greater than the third number.
Add a loop so that your program will continue running until the user wants to exit
example output:
Enter first number
2
Enter second number
3
Enter the third number
4
second number is greater than first number with values 3 and 2
third number is greater than second number with values 4 and 3
third number is greater than first number with values 4 and 2
Exit Program (Y/N)?
Write a program that will display the multiplication table. the number of rows and columns will be entered by the user.
Example output:
Enter a number:
6
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36
User will enter a number. Your program should determine if its odd or even number
Write a program that asks a name, and ask how many times it will print the name
The list holds multiple values in a single variable. It is also called arrays. If you want to store multiple values without creating multiple variables, you can use a list.
Using Lists:
void main() {
List<String> names = ['John', 'James', 'Peter', 'Paul'];
}
counting the length of the list
int length = names.length;
accessing the value on the list
names[0]
Getting the index of a value
names.indexOf("Peter")
An unordered collection of unique items is called set in dart. You can store unique data in sets.
Note: Set doesn’t print duplicate items
void main() {
Set<String> weekdays = {"Sun", "Mon", "Tue", "Wed"};
print(weekdays);
}
Adding to sets
weekdays.add("Thursday");
weekdays.add("Fri");
weekdays.add("Sat");
removing from sets
weekdays.remove("Sun");
Example:
void main() {
Set<String> weekdays = {"Sun", "Mon", "Tue", "Wed"};
print(weekdays);
weekdays.add("Thursday");
weekdays.add("Fri");
weekdays.add("Sat");
print(weekdays);
weekdays.remove("Sun");
print(weekdays);
}
Class is a blueprint of objects and class in the collection of data members and data function. This include getter, setter and constructor and functions.
class class_name {
}
Example:
class MenuItem {
String name;
double price;
MenuItem(this.name, this.price);
String display() {
return "$name : $price";
}
}
void main() {
var myfood = MenuItem('Burger', 5.99);
print(myfood.name);
print(myfood.display());
}
class MenuItem {
String name;
double price;
MenuItem(this.name, this.price);
String display() {
return "$name : $price";
}
}
class Shawarma extends MenuItem {
double discount;
Shawarma(this.discount, super.name, super.price);
String display() {
return "$name : $price - $discount = ${price - discount}";
}
}
void main() {
var myfood = MenuItem('Burger', 5.99);
var shawarma = Shawarma(0.100, 'chicken', 1.5);
print(myfood.name);
print(myfood.display());
print(shawarma.display());
}