createState()
@override
_ExampleState createState() => _ExampleState();
initState()
super.initState()
to ensure the parent class is also initialized properly.@override
void initState() {
super.initState();
// Initialization code here
}
didChangeDependencies()
initState()
and whenever the widget’s dependencies change. Dependencies can change if the widget depends on an InheritedWidget
that itself changes.@override
void didChangeDependencies() {
super.didChangeDependencies();
// Respond to dependency changes
}
build()
build()
method can be called multiple times during the widget's lifecycle, especially after calling setState()
.@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful Widget Lifecycle'),
),
body: Center(
child: Text('Hello, World!'),
),
);
}
setState()
void _incrementCounter() {
setState(() {
_counter++;
});
}
dispose()
dispose()
, the widget is no longer active, and its State object is considered dead.@override
void dispose() {
// Clean up resources
super.dispose();
}
Key Principles of Material Design:
Key Principles of Cupertino Design:
Row
widget in Flutter is used to display its children widgets in a horizontal array. It arranges its children in a single horizontal line, which can be useful for creating layouts where you want elements to be aligned side-by-side.Key Properties of the Row
Widget
MainAxisAlignment.start
: Aligns children to the start of the row.MainAxisAlignment.end
: Aligns children to the end of the row.MainAxisAlignment.center
: Centers children within the row.MainAxisAlignment.spaceBetween
: Distributes children evenly with space between them.MainAxisAlignment.spaceAround
: Distributes children evenly with space around them.MainAxisAlignment.spaceEvenly
: Distributes children evenly with equal space between them.CrossAxisAlignment.start
: Aligns children to the start of the row (top for horizontal rows).CrossAxisAlignment.end
: Aligns children to the end of the row (bottom for horizontal rows).CrossAxisAlignment.center
: Centers children within the row vertically.CrossAxisAlignment.stretch
: Stretches children to fill the vertical space.MainAxisSize.max
: The row takes up as much horizontal space as possible.MainAxisSize.min
: The row only takes up as much horizontal space as needed by its children.Column
widget in Flutter is used to display its children widgets in a vertical array. It arranges its children in a single vertical line, which is useful for creating layouts where you want elements to be stacked one on top of the other.Key Properties of the Column
Widget
MainAxisAlignment.start
: Aligns children to the top of the column.MainAxisAlignment.end
: Aligns children to the bottom of the column.MainAxisAlignment.center
: Centers children within the column.MainAxisAlignment.spaceBetween
: Distributes children evenly with space between them.MainAxisAlignment.spaceAround
: Distributes children evenly with space around them.MainAxisAlignment.spaceEvenly
: Distributes children evenly with equal space between them.CrossAxisAlignment.start
: Aligns children to the start of the column (left for vertical columns).CrossAxisAlignment.end
: Aligns children to the end of the column (right for vertical columns).CrossAxisAlignment.center
: Centers children within the column horizontally.CrossAxisAlignment.stretch
: Stretches children to fill the horizontal space.MainAxisSize.max
: The column takes up as much vertical space as possible.MainAxisSize.min
: The column only takes up as much vertical space as needed by its children.Container
widget in Flutter is a versatile and flexible widget used to create rectangular visual elements. It can be used for a variety of purposes such as adding padding, margins, borders, and background colors, or for positioning widgets in a specific layout.Key Properties of the Container
Widget
Alignment.center
, Alignment.topLeft
, Alignment.bottomRight
, etc.EdgeInsets
(e.g., EdgeInsets.all(16.0)
).EdgeInsets
(e.g., EdgeInsets.all(16.0)
).BoxDecoration
(e.g., BoxDecoration(color: Colors.blue, borderRadius: BorderRadius.circular(10))
).import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Container Widget Example')),
body: ContainerExample(),
),
));
}
class ContainerExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.all(16.0),
width: 200,
height: 100,
color: Colors.blue,
child: Text(
'Blue Container',
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 20),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Text(
'Green Container with Shadow',
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 20),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.all(16.0),
width: 200,
height: 100,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.purple, Colors.orange],
),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'Gradient Container',
style: TextStyle(color: Colors.white),
),
),
],
),
);
}
}
Text('Hello, world!')
ElevatedButton(
onPressed: () {
// Action when button is pressed
},
child: Text('Press Me'),
)
Image.network('<https://example.com/myimage.jpg>')
GestureDetector(
onTap: () {
print('Tapped!');
},
child: Container(
color: Colors.blue,
width: 100,
height: 100,
child: Center(
child: Text('Tap Me'),
),
),
)
GestureDetector(
onLongPress: () {
print('Long Pressed!');
},
child: Container(
color: Colors.green,
width: 100,
height: 100,
child: Center(
child: Text('Long Press Me'),
),
),
)
GestureDetector(
onPanUpdate: (details) {
print('Swiped: ${details.delta}');
},
child: Container(
color: Colors.red,
width: 100,
height: 100,
child: Center(
child: Text('Swipe Me'),
),
),
)
This architecture promotes separation of concerns, making it easier to manage, test, and maintain the application. Each layer has a distinct responsibility, ensuring that changes in one part of the application do not negatively impact other parts.
Key Components of Dart
Key Features
Easy to Understand:
Object-Oriented Programming (OOP):
Open Source:
Browser Support:
Type Safe:
Flexible Compilation and Execution:
Asynchronous Programming:
void main() async {
print('Start');
await Future.delayed(Duration(seconds: 2), () {
print('Hello after 2 seconds');
});
print('End');
}
// Single Variables
type variable_name;
// Multiple Variable
type variable1, variable2, variable3;
Types of Variable:
Static
VariablesDynamic
VariablesFinal
or Const
VariablesRules for variable
void main() {
int age = 30;
double height = 5.9;
bool isStudent = false;
String name = "Alice", city = "Wonderland";
print(age); // Output: 30
print(height); // Output: 5.9
print(isStudent); // Output: false
print(name); // Output: Alice
print(city); // Output: Wonderland
}
Dynamic Variables
dynamic
keyword.void main() {
dynamic item = "Book";
print(item); // Output: Book
item = 10;
print(item); // Output: 10
}
Final and Const Variable
final name = "Alice";
final String city = "Wonderland";
const pi = 3.14;
const String greeting = "Hello";
Null Safety in Dart
?
void main() {
int? age;
age = null;
print(age); // Output: null
}
void main() {
// Declare an integer
int num1 = 10;
print(num1); // Output: 10
}
void main() {
// Declare a double value
double num2 = 10.5;
print(num2); // Output: 10.5
}
void main() {
// Use num to hold different types of numbers
num num1 = 10; // an integer
num num2 = 10.5; // a double
print(num1); // Output: 10
print(num2); // Output: 10.5
}
Parsing Strings to Numbers
parse()
function.void main() {
// Parsing strings to numbers
var num1 = num.parse("5");
var num2 = num.parse("3.14");
// Adding parsed numbers
var sum = num1 + num2;
print("Sum = $sum"); // Output: Sum = 8.14
}
Properties of Number
hashCode
: Gets the hash code of the number.isFinite
: Checks if the number is finite (not infinite).isInfinite
: Checks if the number is infinite.isNaN
: Checks if the number is 'Not a Number' (NaN).isNegative
: Checks if the number is negative.sign
: Returns -1 for negative numbers, 0 for zero, and 1 for positive numbers.isEven
: Checks if the number is even.isOdd
: Checks if the number is odd.Methods for Number
void main() {
int number = -5;
print(number.abs()); // Output: 5
}
void main() {
double number = 3.14;
print(number.ceil()); // Output: 4
}
void main() {
double number = 3.14;
print(number.floor()); // Output: 3
}
void main() {
int number1 = 10;
int number2 = 20;
print(number1.compareTo(number2)); // Output: -1
}
void main() {
int dividend = 10;
int divisor = 3;
print(dividend.remainder(divisor)); // Output: 1
}
void main() {
double number = 3.6;
print(number.round()); // Output: 4
}
void main() {
int number = 10;
print(number.toDouble()); // Output: 10.0
}
void main() {
double number = 10.5;
print(number.toInt()); // Output: 10
}
void main() {
int number = 10;
print(number.toString()); // Output: "10"
}
void main() {
double number = 10.9;
print(number.truncate()); // Output: 10
}
'
) or double quotes ( "
). Both types of quotes work the same way.void main() {
String greeting = 'Hello, Dart!';
print(greeting); // Output: Hello, Dart!
}
+
operator.void main() {
String firstName = 'John';
String lastName = 'Doe';
String fullName = firstName + ' ' + lastName;
print(fullName); // Output: John Doe
}
${}
within double quoted strings.void main() {
String name = 'Alice';
int age = 30;
String introduction = 'Hello, my name is $name and I am $age years old.';
print(introduction); // Output: Hello, my name is Alice and I am 30 years old.
}
void main() {
String name = 'Bob';
String greeting = 'Hi, $name!';
print(greeting); // Output: Hi, Bob!
}
'''
or """
).void main() {
String multiLine = '''This is a string
that spans across multiple
lines.''';
print(multiLine);
// Output:
// This is a string
// that spans across multiple
// lines.
}
String Methods
String.fromCharCodes(Iterable charCodes)
: Creates a string from a list of character codes.String.fromCharCode(int charCode)
: Creates a string from a single character code.String.fromEnvironment(String name, {String defaultValue})
: Gets a string from environment variables.codeUnitAt(int index)
: Returns the UTF-16 code unit at the specified index.runes
: Returns an iterable of the Unicode code points of the string.characters
: Returns an iterable of the string's characters (requires the characters package).contains(Pattern pattern, [int start = 0])
: Checks if the string contains the specified pattern.startsWith(Pattern pattern, [int start = 0])
: Checks if the string starts with the specified pattern.endsWith(String other)
: Checks if the string ends with the specified string.isEmpty
: Checks if the string is empty.isNotEmpty
: Checks if the string is not empty.length
: Returns the number of characters in the string.toLowerCase()
: Converts all characters in the string to lowercase.toUpperCase(
) : Converts all characters in the string to uppercase.trim()
: Removes leading and trailing whitespace from the string.trimLeft()
: Removes leading whitespace from the string.trimRight()
: Removes trailing whitespace from the string.replaceAll(Pattern from, String replace)
: Replaces all occurrences of a pattern with a new string.replaceFirst(Pattern from, String to, [int startIndex = 0])
: Replaces the first occurrence of a pattern with a new string.replaceRange(int start, int end, String replacement)
: Replaces the substring from start to end with a new string.padLeft(int width, [String padding = ' '])
: Pads the string on the left to the specified width.padRight(int width, [String padding = ' '])
: Pads the string on the right to the specified width.substring(int start, [int end])
: Returns the substring from start to end.split(Pattern pattern)
: Splits the string at each occurrence of the pattern and returns a list of substrings.join(Iterable strings
) : Joins a list of strings into a single string.compareTo(String other)
: Compares this string to another string.==
(equality operator): Checks if two strings are equal.hashCode
: Returns the hash code for the string.String name = 'World'; print('Hello, $name!');
replaceAllMapped(Pattern from, String replace(Match match))
: Replaces all occurrences of a pattern with a new string computed from a function.void main() {
String str = 'Hello, World!';
// Accessing Characters
print(str.codeUnitAt(0)); // Output: 72
print(str.runes
.toList()); // Output: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
// Querying Strings
print(str.contains('World')); // Output: true
print(str.startsWith('Hello')); // Output: true
print(str.endsWith('!')); // Output: true
print(str.isEmpty); // Output: false
print(str.isNotEmpty); // Output: true
print(str.length); // Output: 13
// Manipulating Strings
print(str.toLowerCase()); // Output: hello, world!
print(str.toUpperCase()); // Output: HELLO, WORLD!
print(str.trim()); // Output: Hello, World!
print(str.replaceAll('World', 'Dart')); // Output: Hello, Dart!
print(str.substring(0, 5)); // Output: Hello
print(str.split(', ')); // Output: [Hello, World!]
print(str.padLeft(15, '*')); // Output: **Hello, World!
print(str.padRight(15, '*')); // Output: Hello, World!**
// Interpolating and Formatting Strings
String name = 'Dart';
print('Hello, $name!'); // Output: Hello, Dart!
// Advanced Replacement
String text = 'The quick brown fox';
String newText = text.replaceAllMapped(
RegExp(r'\\b\\w'), (match) => match.group(0)!.toUpperCase());
print(newText); // Output: The Quick Brown Fox
}
true
or false
.void main() {
// Declare boolean variables
bool isDay = true;
bool isNight = false;
// Print the values
print("Is it day? $isDay");
print("Is it night? $isNight");
}
void main() {
List<int> numbers = []; // Empty list of integers
numbers.add(10); // Add elements to the list
numbers.add(20);
numbers.add(30);
print(numbers); // Output: [10, 20, 30]
}
void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
print(fruits); // Output: [Apple, Banana, Cherry]
}
void main() {
List<String> fixedList = List<String>.filled(3, 'default');
fixedList[0] = 'Hello';
fixedList[1] = 'World';
fixedList[2] = 'Dart';
print(fixedList); // Output: [Hello, World, Dart]
}
void main() {
List<int> generatedList = List<int>.generate(5, (index) => index * 2);
print(generatedList); // Output: [0, 2, 4, 6, 8]
}
void main() {
List<String> colors = ['Red', 'Green', 'Blue'];
print(colors[0]); // Output: Red
print(colors[1]); // Output: Green
print(colors[2]); // Output: Blue
}
void main() {
List<String> animals = ['Cat', 'Dog', 'Bird'];
animals[1] = 'Fish'; // Change 'Dog' to 'Fish'
print(animals); // Output: [Cat, Fish, Bird]
}
List Methods
add(E value)
: Adds a single element to the end of the list.addAll(Iterable iterable)
: Adds all elements of the given iterable to the end of the list.remove(Object value)
: Removes the first occurrence of the value from the list.removeAt(int index)
: Removes the element at the specified index.removeLast()
: Removes the last element of the list.removeRange(int start, int end)
: Removes elements from the specified range.elementAt(int index)
: Returns the element at the specified index.first
: Gets the first element of the list.last
: Gets the last element of the list.single
: Gets the single element of the list, assuming the list has only one element.indexOf(E element)
: Returns the first index of the element, or -1 if not found.lastIndexOf(E element)
: Returns the last index of the element, or -1 if not found.[]
(index operator): Access or update the element at the specified index.insert(int index, E element)
: Inserts an element at the specified index.insertAll(int index, Iterable iterable)
: Inserts all elements of the given iterable at the specified index.contains(Object element)
: Checks if the list contains the specified element.isEmpty
: Checks if the list is empty.isNotEmpty
: Checks if the list is not empty. length : Returns the number of elements in the list.sort([int compare(E a, E b)])
: Sorts the list in place according to the provided comparison function.reversed
: Returns an iterable with the elements of the list in reverse order.sublist(int start, [int end])
: Returns a new list containing the elements in the specified range.fillRange(int start, int end, [E fillValue])
: Replaces the elements in the specified range with the given value.replaceRange(int start, int end, Iterable newContents)
: Replaces the elements in the specified range with the given iterable.map(T f(E e))
: Returns a new iterable with the results of applying the function to each element.where(bool test(E element))
: Returns a new iterable with all elements that satisfy the test.forEach(void f(E element))
: Applies the function to each element of the list.reduce(T combine(T value, E element))
: Reduces the list to a single value by repeatedly applying the combine function.fold(T initialValue, T combine(T previousValue, E element))
: Similar to reduce , but allows specifying an initial value.join([String separator = ""])
: Returns a string representation of the list, joined by the separator.toList({bool growable = true})
: Returns a new list containing the elements of the iterable.clear()
: Removes all elements from the list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Add elements
numbers.add(6);
numbers.addAll([7, 8, 9]);
// Remove elements
numbers.remove(2);
numbers.removeAt(0);
numbers.removeLast();
// Access elements
print(numbers[0]); // Output: 3
print(numbers.first); // Output: 3
print(numbers.last); // Output: 8
// Update elements
numbers[0] = 10;
numbers.insert(1, 15);
// Query list
print(numbers.contains(15)); // Output: true
print(numbers.isEmpty); // Output: false
print(numbers.length); // Output: 6
// Sort and reverse
numbers.sort();
print(numbers); // Output: [3, 4, 5, 6, 7, 10, 15]
print(numbers.reversed.toList()); // Output: [15, 10, 7,6, 5, 4, 3]
// Sublist and ranges
print(numbers.sublist(1, 3)); // Output: [4, 5]
numbers.fillRange(0, 2, 99);
print(numbers); // Output: [99, 99, 5, 6, 7, 10, 15]
// Transformation
var mapped = numbers.map((e) => e * 2).toList();
print(mapped); // Output: [198, 198, 10, 12, 14, 20, 30]
// Copy and clear
var copy = numbers.toList();
numbers.clear();
print(numbers); // Output: []
print(copy); // Output: [99, 99, 5, 6, 7, 10, 15]
}
void main() {
// Declaring an empty map
Map<String, String> emptyMap = {};
// Adding key-value pairs
emptyMap['name'] = 'John';
emptyMap['city'] = 'New York';
print(emptyMap); // Output: {name: John, city: New York}
}
void main() {
// Declaring a map with initial values
Map<String, int> ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
print(ages); // Output: {Alice: 30, Bob: 25, Charlie: 35}
}
void main() {
Map<String, String> capitals = {
'USA': 'Washington, D.C.',
'France': 'Paris',
'Japan': 'Tokyo'
};
// Accessing a value
print(capitals['France']); // Output: Paris
// Modifying a value
capitals['Japan'] = 'Kyoto'; // Change Tokyo to Kyoto
print(
capitals); // Output: {USA: Washington, D.C., France: Paris, Japan: Kyoto}
}
Map Methods
putIfAbsent(K key, V ifAbsent())
: Adds a key-value pair to the map if the key is not already present.addAll(Map other)
: Adds all key-value pairs from another map to the current map.update(K key, V update(V value), {V ifAbsent()})
: Updates the value for the provided key, or adds it if it does not exist.updateAll(V update(K key, V value))
: Updates all values in the map by applying the provided function.remove(Object key)
: Removes the value for the specified key from the map.clear()
: Removes all key-value pairs from the map.[]
(index operator): Accesses the value associated with the specified key.containsKey(Object key)
: Checks if the map contains the specified key.containsValue(Object value)
: Checks if the map contains the specified value.entries
: Returns an iterable of the key-value pairs in the map.keys
: Returns an iterable of the keys in the map.values
: Returns an iterable of the values in the map.isEmpty
: Checks if the map is empty.isNotEmpty
: Checks if the map is not empty.length
: Returns the number of key-value pairs in the map.map(MapEntry transform(K key, V value))
: Returns a new map with the results of applying the transform function to each key-value pair.forEach(void action(K key, V value))
: Applies the function to each key-value pair in the map.putIfAbsent(K key, V ifAbsent())
: Returns the value for the specified key, or adds the key with a value computed by ifAbsent()
and returns that value.void main() {
Map<String, int> map = {'a': 1, 'b': 2, 'c': 3};
// Adding and updating elements
map['d'] = 4; // Add new key-value pair
map.putIfAbsent('e', () => 5); // Add if key is absent
map.update('a', (value) => value + 1); // Update existing value
map.updateAll((key, value) => value * 2); // Update allvalues
// Removing elements
map.remove('b'); // Remove key-value pair by key
map.clear(); // Clear all key-value pairs
// Accessing elements
map = {'a': 1, 'b': 2, 'c': 3};
print(map['a']); // Access value by key, Output: 1
print(map.containsKey('a')); // Check if key exists, Output: true
print(map.containsValue(2)); // Check if value exists, Output: true
// Querying map
print(map.isEmpty); // Check if map is empty, Output: false
print(map.isNotEmpty); // Check if map is not empty, Output: true
print(map.length); // Get the number of key-value pairs,Output: 3
// Transforming maps
map.forEach((key, value) {
print('Key: $key, Value: $value');
});
// Output:
// Key: a, Value: 1
// Key: b, Value: 2
// Key: c, Value: 3
var newMap = map.map((key, value) => MapEntry(key, value * 10));
print(newMap); // Output: {a: 10, b: 20, c: 30}
// Getting default values
var value = map.putIfAbsent('d', () => 4);
print(value); // Output: 4
print(map); // Output: {a: 1, b: 2, c: 3, d: 4}
// Accessing keys and values
print(map.keys); // Output: (a, b, c, d)
print(map.values); // Output: (1, 2, 3, 4)
// Entries
print(map
.entries); // Output: (MapEntry(a: 1), MapEntry(b: 2), MapEntry(c: 3), MapEntry(d: 4))
}
/// This sis Documentation Comment
/// This function prints a greeting message
// This is a single line comment
/* This is
a multi line
comment */
print("Hello World")
+
(Addition): Adds two numbers.-
(Subtraction): Subtracts one number from another.*
(Multiplication): Multiplies two numbers./
(Division): Divides one number by another and gives a decimal result.~/
(Integer Division): Divides and gives the whole number part of the result.%
(Modulus): Gives the remainder of a division.void main() {
int a = 2;
int b = 3;
print("Sum (a + b) = ${a + b}");
print("Difference (a - b) = ${a - b}");
print("Negation (-(a - b)) = ${-(a - b)}");
print("Product (a * b) = ${a * b}");
print("Division (b / a) = ${b / a}");
print("Quotient (b ~/ a) = ${b ~/ a}");
print("Remainder (b % a) = ${b % a}");
}
>
(Greater than): Checks if one value is larger than another.<
(Less than): Checks if one value is smaller than another>=
(Greater than or equal to): Checks if one value is larger or equal to another.<=
(Less than or equal to): Checks if one value is smaller or equal to another.==
(Equal to): Checks if two values are the same.!=
(Not equal to): Checks if two values are different.void main() {
int a = 2;
int b = 3;
print("a > b: ${a > b}");
print("a < b: ${a < b}");
print("a >= b: ${a >= b}");
print("a <= b: ${a <= b}");
print("a == b: ${a == b}");
print("a != b: ${a != b}");
}
is
: Checks if a value is of a specific type.is!
: Checks if a value is not of a specific type.void main() {
String a = 'Hello';
double b = 3.3;
print(a is String); // true
print(b is! int); // true
}
=
(Equal to): Assigns a value to a variable.??=
(Null-aware assignment): Assigns a value only if the variable is null .void main() {
int a = 5;
int b = 7;
var c = a * b;
print("c = $c");
var d;
d ??= a + b;
print("d = $d");
d ??= a - b;
print("d = $d"); // d remains 12
}
&&
(AND): Returns true
if both conditions are true .||
(OR): Returns true
if at least one condition is true .!
(NOT): Reverses the result of a condition.void main() {
bool a = true;
bool b = false;
print("a && b: ${a && b}"); // false
print("a || b: ${a || b}"); // true
print("!a: ${!a}"); // false
}
condition ? expression1 : expression2
: Executes expression1 if condition is true , otherwise expression2 .expression1 ?? expression2
: Returns expression1 if it's not null , otherwise expression2 .void main() {
int a = 5;
var result = (a < 10) ? "Correct" : "Wrong";
print(result);
int? n;
var value = n ?? "n is null";
print(value);
n = 10;
value = n;
print(value);
}
..
(Cascade): Allows you to call multiple methods on the same objectclass Calc {
int a = 0;
int b = 0;
void set(x, y) {
this.a = x;
this.b = y;
}
void add() {
var z = this.a + this.b;
print(z);
}
}
void main() {
Calc calculator = new Calc();
Calc calculator2 = new Calc();
calculator.set(1, 2);
calculator.add();
calculator2
..set(3, 4)
..add();
}
To read input from the user, you need to use the dart:io
library. This library allows you to access the standard input (keyboard) and output (console).
The stdin.readLineSync()
function is commonly used to read user input as a string.
Here’s how to take a string input from the user
import 'dart:io';
void main() {
print("Enter your name:");
// Reading the user's name
String? name = stdin.readLineSync();
// Printing a greeting message
print("Hello, $name! \\nWelcome to Dart!!");
}
int.parse()
import 'dart:io';
void main() {
print("Enter your favourite number:");
// Reading and converting input to integer
int? number = int.parse(stdin.readLineSync()!);
// Printing the number
print("Your favourite number is $number");
}
print()
function adds a newline after the outputimport 'dart:io';
void main() {
print("Welcome to Dart!");
}
stdout.write()
function prints text without adding a newlineimport 'dart:io';
void main() {
stdout.write("Welcome to Dart!");
}
print()
: Moves to the next line after printing.stdout.write
: Stays on the same line.if
Statementif
statement is used to execute a block of code if a specified condition is true.void main() {
int number = 10;
if (number > 5) {
print('The number is greater than 5');
}
}
if-else
Statementif-else
statement allows you to execute one block of code if a condition is true and another block if the condition is falsevoid main() {
int number = 3;
if (number > 5) {
print('The number is greater than 5');
} else {
print('The number is 5 or less');
}
}
if-else if-else
Statementvoid main() {
int number = 7;
if (number > 10) {
print('The number is greater than 10');
} else if (number > 5) {
print('The number is greater than 5 but 10 or less');
} else {
print('The number is 5 or less');
}
}
switch
Statementswitch
statement is used to select one of many code blocks to execute.void main() {
String day = 'Monday';
switch (day) {
case 'Monday':
print('Start of the work week');
break;
case 'Friday':
print('End of the work week');
break;
case 'Saturday':
case 'Sunday':
print('Weekend');
break;
default:
print('Invalid day');
}
}
if-else
statements. It allows you to write a simple conditional statement in a single line.void main() {
int number = 10;
String result =
number > 5 ? 'The number is greater than 5' : 'The number is 5 or less';
print(result);
}
for
Loopfor
loop is used to execute a block of code a specific number of times.void main() {
for (int i = 0; i < 5; i++) {
print(i);
}
}
while
Loopwhile
loop repeatedly executes a block of code as long as a specified condition is true.void main() {
int i = 0;
while (i < 5) {
print(i);
i++;
}
}
do-while
Loopdo-while
loop is similar to the while
loop but ensures that the code block is executed at least once before checking the condition.void main() {
int i = 0;
do {
print(i);
i++;
} while (i < 5);
}
for-in
Loopfor-in
loop is used to iterate over elements in a collection such as a list or a map.void main() {
List<String> fruits = ['Apple', 'Banana', 'Cherry'];
for (var fruit in fruits) {
print(fruit);
}
}
break
Statementbreak
statement is used to exit a loop before its condition becomes false. It immediately terminates the innermost loop.void main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
print(i);
}
}
continue
Statementcontinue
statement is used to skip the rest of the code inside the current iteration of a loop and proceed with the next iteration.void main() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
print(i);
}
}
break
and continue
statements to specify which loop to break out of or continue. This is useful in nested loops.outerLoop: for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 3) {
break outerLoop;
}
print('$i, $j');
}
}
print()
, int.parse()
, List.add()
, sqrt()
etc are built-in functionsreturnType
followed by the functionName
, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.int add(int a, int b) {
return a + b;
}
void main() {
int result = add(5, 3);
print(result); // Output: 8
}
void
as the return type.void greet(String name) {
print('Hello, $name!');
}
void printDetails(String name, [int age = 0]) {
print('Name: $name, Age: $age');
}
void main() {
printDetails('Alice'); // Output: Name: Alice, Age: 0
printDetails('Bob', 25); // Output: Name: Bob, Age: 25
}
void printDetails({required String name, int age = 0}) {
print('Name: $name, Age: $age');
}
void main() {
printDetails(name: 'Alice'); // Output: Name: Alice, Age: 0
printDetails(name: 'Bob', age: 25); // Output: Name: Bob, Age: 25
}
int add(int a, int b) => a + b;
void main() {
var numbers = [1, 2, 3, 4];
// Anonymous Function
var doubled = numbers.map((number) => number * 2);
print(doubled); // Output: (2, 4, 6, 8)
}
void performOperation(int a, int b, int Function(int, int) operation) {
print(operation(a, b));
}
int add(int x, int y) => x + y;
int multiply(int x, int y) => x * y;
void main() {
performOperation(5, 3, add); // Output: 8
performOperation(5, 3, multiply); // Output: 15
}
Origin:
Availability:
Flexibility:
When to Use Each:
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to design and structure software.
Dart, being an object-oriented language, allows you to use OOP principles to create reusable, modular, and maintainable code
Class: A blueprint for creating objects. It defines the properties (attributes) and methods (functions) that the objects created from the class will have.
Object: An instance of a class. It is created based on the class blueprint and can use the properties and methods defined in the class.
// Define a class
class Person {
// Properties
String name;
int age;
// Constructor
Person(this.name, this.age);
// Method
void greet() {
print('Hello, my name is $name and I am $age years old.');
}
}
void main() {
// Create an object of the class
Person person = Person('Alice', 30);
person.greet(); // Output: Hello, my name is Alice and I am 30 years old.
}
this
Keywordthis
Keyword
this
to access instance variables and methods of the current object.this
to differentiate between instance variables and parameters or local variables when they have the same name.this
to pass the current object as a parameter to other methods or constructors.this
to clarify that you are referring to the current object's variables.class Person {
String name;
int age;
Person(this.name,
this.age); // Constructor with parameter names same as instance variables
void printInfo() {
print('Name: ${this.name}');
print('Age: ${this.age}');
}
}
void main() {
Person person = Person('Alice', 30);
person.printInfo();
}
this
helps to distinguish themclass Rectangle {
int width;
int height;
Rectangle(int width, int height) {
this.width = width; // `this.width` refers to the instance variable
this.height = height; // `this.height` refers to the instance variable
}
void display() {
print('Width: $width, Height: $height');
}
}
void main() {
Rectangle rect = Rectangle(10, 20);
rect.display();
}
this
to pass the current object as a parameter to other methods or constructors.class Box {
int length;
Box(this.length);
void describe(Box other) {
print('Comparing this box with another box of length ${other.length}');
}
void compare() {
describe(this); // Passing the current object to the method
}
}
void main() {
Box box1 = Box(15);
Box box2 = Box(10);
box1.compare();
// Output: Comparing this box with another box of length 15
}
class BankAccount {
// Private property
double _balance;
// Constructor
BankAccount(this._balance);
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
_balance += amount;
}
}
// Method to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= _balance) {
_balance -= amount;
}
}
// Method to get the balance
double getBalance() {
return _balance;
}
}
void main() {
BankAccount account = BankAccount(1000);
account.deposit(500);
account.withdraw(200);
print('Balance: ${account.getBalance()}'); // Output: Balance: 1300.0
}
extends
keyword to inherit a classObject
class by default.// Parent class
class Animal {
void eat() {
print('Animal is eating');
}
}
// Child class inheriting from Animal
class Dog extends Animal {
void bark() {
print('Dog is barking');
}
}
void main() {
var dog = Dog();
dog.eat(); // Inherited method
dog.bark(); // Method of the subclass
}
// Grandparent class
class Animal {
void eat() {
print('Animal is eating');
}
}
// Parent class
class Dog extends Animal {
void bark() {
print('Dog is barking');
}
}
// Child class inheriting from Dog
class Labrador extends Dog {
void play() {
print('Labrador is playing fetch');
}
}
void main() {
var labrador = Labrador();
labrador.eat(); // Inherited from Animal
labrador.bark(); // Inherited from Dog
labrador.play(); // Method of the subclass
}
// Parent class
class Animal {
void eat() {
print('Animal is eating');
}
}
// Child class 1
class Dog extends Animal {
void bark() {
print('Dog is barking');
}
}
// Child class 2
class Cat extends Animal {
void meow() {
print('Cat is meowing');
}
}
void main() {
var dog = Dog();
var cat = Cat();
dog.eat(); // Inherited method
dog.bark(); // Method of Dog
cat.eat(); // Inherited method
cat.meow(); // Method of Cat
}
// Base class
class Shape {
void draw() {
print('Drawing a shape.');
}
}
// Subclass
class Circle extends Shape {
@override
void draw() {
print('Drawing a circle.');
}
}
// Subclass
class Square extends Shape {
@override
void draw() {
print('Drawing a square.');
}
}
void main() {
Shape shape1 = Circle();
Shape shape2 = Square();
shape1.draw(); // Output: Drawing a circle.
shape2.draw(); // Output: Drawing a square.
}
// Abstract class
abstract class Shape {
void draw(); // Abstract method
}
// Concrete class
class Triangle extends Shape {
@override
void draw() {
print('Drawing a triangle.');
}
}
void main() {
Shape shape = Triangle();
shape.draw(); // Output: Drawing a triangle.
}
class Car {
String make;
String model;
// Default constructor
Car(this.make, this.model);
// Named constructor
Car.withDefaults()
: make = 'Unknown',
model = 'Unknown';
}
void main() {
Car car1 = Car('Toyota', 'Corolla');
print('Car 1: ${car1.make} ${car1.model}');
// Output: Car 1: Toyota Corolla
Car car2 = Car.withDefaults();
print('Car 2: ${car2.make} ${car2.model}');
// Output: Car 2: Unknown Unknown
}
Made By SOU Student for SOU Students