1BASIC
1BASIC
1BASIC
Part I
Shan-Hung Wu
CS, NTHU
Let’s Roll Dice
• Today’s topics:
• Dart language
• Flutter app overview
• Stateless vs stateful
widgets
2
Evolution of Dart
• Dart 1.0 (Nov 2013)
• Initially introduced as an alternative to JavaScript
• Pub package manager
• Dart 2.0 (Aug 2018)
• Strong type system
• Sound null safety
• Supports Flutter!
• Dart 3.0 (May 2023)
• Null Safety by default
• Unified dev workflow across different platforms
3
Dart Features
• Platform-independent (Windows, Mac, Linux, and Web)
• Just-In-Time (JIT) compilation in development
• Runs in VM; offering hot reload
• Ahead-Of-Time (AOT) compilation in production
• Native code or JavaScript; high performance
• Auto memory management with Garbage Collection (GC)
• Function as first-class citizen
• Sound null safety
• Object-oriented
• Supports encapsulation, inheritance, polymorphism, interface,
extension, etc.
• Async, await, and concurrency (Isolates)
• Foreign Function Interface (FFI)
• Free and open-source
4
Warm up:
5
Terms Revisited
• Statement: command that ends with “;”
• print('Hello world!');
• Expression: command evaluated to a single value
• 'Hello ' + 'world!'
• Keyword: word reserved for compiler
• int, String, if, for, static, final, etc.
• Identifier: name of variable, function, class, etc.
• int age;
• Literal: value directly written in source code
• double pi = 3.14;
6
Hello World!
void main() {
print('Enter your name:');
String? name = stdin.readLineSync();
if (name != null) {
print('Hello ${name}');
}
}
• Package dart:io provided by Dart
• Only runs in command line via dart run
• String? means “name could be null”
• We will discuss this feature later
9
Built-in Data Types
bool • All types are object types
int • Extending Object class
double • Passed “by reference”, not “by value”
num // int or double
runs // String's Unicode
String
List
Set
Map
Function
void main() {
var bob = ...;
changeName(bob);
}
void changeName(Map person) { ... }
10
Immutable Types
• bool, int, double and String types are immutable
• 'Hello ' + 'world!' creates new String object
11
Memory Management
13
Iterating Lists & Maps
• List: for (var e in myList) {
print(e);
}
void main(){
// 10 and 20 are arguments
add(10, 20);
}
15
Parameters & Default Values
// Optional positional parameters
void sayMessage(String message, [String? author]) {
print("$message — ${author ?? 'Anonymous'}");
}
void main() {
sayMessage('Hello, Dart!');
setDimensions(height: 20, width: 30);
}
17
Multiple Return Values
final json = <String, dynamic>{ // "dynamic" means "any type"
'name': 'Dash',
'age': 10,
'color': 'blue',
};
18
Arrow Functions
• If a function consists of just one line of code that
returns a value, it has simpler syntax:
// Normal function
int add(int a, int b) { return a + b; }
// Arrow function
int add(int a, int b) => a + b;
19
Functions as First-Class Citizens
// Basic operations
int add(int a, int b) => a + b;
int multiply(int a, int b) => a * b;
void main() {
// Assigning functions to variables
Function(int, int) op = add;
printOPResult(4, 2, op);
op = multiply;
printOPResult(4, 2, op); • Functions can be assigned to
} variables and passed around
20
Anonymous Functions
• E.g., list manipulation: • E.g., map manipulation:
for (int e in myList) { for (var k in myMap.keys) {
print(e); print(k);
} }
myList.forEach((e) { myMap.keys.forEach((k) {
print(e); print(k);
}); });
21
Variables are Block-scoped
void outerFunction() {
var outerStr = "I'm outside!";
void innerFunction() {
var innerStr = "I'm inside!";
print(outerStr); // Accessible in nested func!
}
void main() {
var addFrom2 = makeAdder(2);
var addFrom3 = makeAdder(3);
print(addFrom2(10)); // Output: 12
print(addFrom3(10)); // Output: 13
}
void main() {
var counters = createCounters();
for (var counter in counters) {
print(counter()); // Prints 0, 1, 2
}
}
24
Classes & Custom Types
class Person {
// Instance variables
String name; • Class as the blueprint (type)
int age;
of your custom objects
// Constructor
Person({required this.name, required this.age});
// Method
void displayInfo() {
print('Name: $name, Age: $age');
}
}
void main() {
var alice = Person('name': 'Alice', age': 20); // Instance
alice.displayInfo(); // Output: Name: Alice, Age: 20
var bob = Person('name': 'Bob', age': 21); // Instance
bob.displayInfo(); // Output: Name: Bob, Age: 21
// Constructor
Person({required this.name, required this.age});
// Named constructor
Person.fromMap(Map<String, dynamic> data)
: name = data['name'],
age = data['age'];
...
}
void main() {
var map = {'name': 'Dave', 'age': 25};
var person = Person.fromMap(map);
person.displayInfo();
}
26
Inheritance
(1/3) class Student extends Person {
String university;
Student({
required super.name,
required super.age,
required this.university
});
@override
void displayInfo() {
super.displayInfo();
print('University: $university');
}
Student({
required super.name,
required super.age,
required this.company
});
@override
void displayInfo() {
super.displayInfo();
print(Company: $company');
}
void main() {
Person alice = Student(..., university: ...);
alice.displayInfo(); // with "University: ..."
assert(alice is Person);
assert(alice is Student);
assert(alice is! Employee);
29
Entering Flutter
• Project structure
• lib/main.dart
• MaterialApp widget
• build() in widgets
• Defines widget hierarchy
• Button and rollDice()
callback in
dice_roller.dart
• Random() and dynamic
image file name
30
Wait, the App Doesn’t Work
• When button pressed, dice image doesn’t change
as expected
• The rollDice() callback is indeed invoked
• We can verify this by inserting
print(currentDiceRoll)into its body
• What's wrong?
31
Stateless vs. Stateful Widgets
class CounterWidget extends StatefulWidget {
const CounterWidget({super.key});
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0; // Initial counter value
void _incrementCounter() {
setState(() {
_counter++; • setState() tells Flutter to
});
} rerun build() and updates UI
@override
Widget build(BuildContext context) {
return Text('Counter: $_counter');
}
}
32
References
• Introduction to Dart
33