Dart basic grammar

· Tech· Flutter
Flutter

Dart Basic

What is programming?

Program = list of instructions that a computer can understand

Compilation

A compiler converts code written by a person in a high-level language into a low-level language so that the computer can understand it. Just in time (JIT) compilation

  • Translation process during execution - Runtime period AOT compilation
  • Technology to pre-compile before execution
  • Because it is not real-time compilation, development efficiency is low.
Dart uses both compilers (JIT, AOT)
Why should you use Dart?

A language called Dart is used to develop cross-platform apps using Flutter. It is an object-oriented language designed by Google, similar to the C language, and provides simple functional elements like other languages.

  • Productivity is crazy thanks to multi-platform.
  • Supports modern programming - Supports object-oriented, functional, and asynchronous programming
  • There is type safety of data. Type Safe
  • Null Safe
  • int? a = 42; - Nullable can be made null-safe.
  • int a = 42; - It can be made non-nullable and safe against nulls.
SDK, Software Development Kit
  • Compiler, library, debugging and testing tools, documentation and sample code, package manager
  • Dart SDK included in Flutter SDK
  • Version notation
  • Stable version 3.5.2
  • Beta version 3.6.0-218.0.beta
  • Dev version 3.6.0-218.0.dev

Dart basic syntax

variables

Variables whose values can be changed during program execution
  • Numeric type (int, double, num), character type (String), Boolean type (boolean)
  • dynamic is available for all types, and the type is checked at runtime. late only supports types specified at declaration, and types are checked at compile time.
int age = 30;
String name = "Bob";
bool isStudent = true;
var city = 'Seoul';      // 자동추론
dynamic value = 'Hello'; // 런타임에 타입이 결정
Constants (Const)

Variable whose value can change during program execution

  • final - when the value is determined during program execution
  • const - when the value is always fixed
final age = 30;
const age = 30;
// Can't assign to the const variable 'age'.
age = 40;
late

It is a variable that is delayed initialized when the variable is used after declaration, and because it is non-nullable, null cannot be entered. Use when variables with high initialization costs are not needed right away.

late String greeting;
void main() {
greeting = getGreeting();
print(greeting);
}
String getGreeting() {
return "Hello, Dart!";
}
null

Dart has null safety, so basically variables cannot have the value null.

  • By using the ?. (null-aware operator) operator, even null values ​​can be accepted.
String? nullableName;
nullableName = null;
String nonNullableName = 'Bob';
// nonNullableName = null;
// The value 'null' can't be assigned to a variable of type 'String' because 'String' is not nullable.

operator

It is used for mathematical operations, comparisons, and data combinations in programs.

  • Arithmetic operators
  • +, -, *, /
  • ~/ (returns only the integer of the dividing value)
  • % (returns only the remainder of the divided value)
  • Comparison operators
  • ==, !=, >, <, >=, <=
  • Type check operator
  • as (type conversion, only possible if compatible)
  • is (type determination)
  • is! (determines whether it does not have a specific type)
  • Assignment operator
  • =, ??= (When the value on the left is null, substitute the value on the right)
  • +=, -=, *=, /=, ~/=, %=
  • Logical operators
  • !, ||, &&

Enum

This is a type used for constant sets, and unlike Set, it can be used by creating an index. If you try to add a value that already exists, an error will occur.

enum Food {
rice,
noodles,
ramen,
hotdog,
pizza
}

loop

Loop statement using for statement

Items are displayed as a ListTile widget using a for loop. Here, you can see that the item within the items is taken out with var item in items and the code below the for statement is executed. Here, the for statement basically guarantees the list order.

for (var i = 0; i < items.length; i++) {
print(items[i]); // items의 각 항목을 출력
}
for (var item in items) {
listTiles.add(ListTile(title: Text(item))); // 각 항목에 대해 ListTile 추가
}
Loop statement using forEach statement

The forEach statement is also a loop statement that guarantees collection order. Unlike the for statement, it does not directly deal with indices but defines tasks to be executed in a functional style. You cannot use return, break, continue, etc. inside forEach.

items.forEach((item) {
listTiles.add(ListTile(title: Text(item))); // 각 항목에 대해 ListTile 추가
});
Loop statement using while statement

It is a loop statement that continues to perform the tasks within the while loop while the given condition is true.

while (index < items.length) {
listTiles.add(ListTile(title: Text(items[index])));
index++;
}
Loop statement using do-while statement

The first iteration is executed once, with a loop whose condition is later checked. Afterwards, if the conditions are not suitable, the iteration stops.

do {
listTiles.add(ListTile(title: Text(items[index])));
index++;
} while (index < items.length);
Loop using map

This example shows declaring a list variable called items and listing it in the ListTile widget within the scaffold. Here too, list order is guaranteed.

class ListWidget extends StatelessWidget {
final List<String> items = ['사과', '바나나', '체리', '포도', '오렌지']; // 리스트 데이터
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('반복문 예제')),
body: ListView(
children: items.map((item) => ListTile(title: Text(item))).toList(), // 반복문 적용
),
);
}
}
break, continue

break and continue are used to control flow in loops. break completely terminates the loop, and continue skips the current iteration and moves on to the next iteration. When i is 5, the loop ends and the loop that repeats up to 10 is not continued. That is, 0, 1, 2, 3, and 4 are output.

void main() {
for (var i = 0; i < 10; i++) {
if (i == 5) {
print('i가 5일 때 반복문 종료');
break;
}
print(i);
}
}

Only when i is 5, the current iteration is skipped, and 0, 1, 2, 3, 4, 6, 7, 8, and 9 are output in the next iteration. You can see that the skipped 5 is not printed.

void main() {
for (var i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
print(i);
}
}

Conditional statement

Conditional statement using if statement

It sequentially checks using conditional statements using if, else if, else, and executes the code block if the condition is met.

int number = 7;
if (number > 10) {
print("number는 10보다 큽니다.");
} else if (number > 5) {
print("number는 5보다 크고 10보다 작거나 같습니다.");
} else {
print("number는 5보다 작거나 같습니다.");
}
Conditional statement using switch statement

A switch statement selects one of several values and executes the corresponding block of code.

String fruit = "사과";
switch (fruit) {
case "사과":
print("사과입니다.");
break;
case "바나나":
print("바나나입니다.");
break;
case "포도":
print("포도입니다.");
break;
default:
print("알 수 없는 과일입니다.");
}

Conditional expression

Conditional statements using conditional expressions

If the condition before ? is met, the value before : is assigned to the variable. If the condition is not met, the value after : is assigned to the variable.

int number = 8;
String result = (number > 5) ? "5보다 큽니다" : "5보다 작거나 같습니다";
print(result);
Conditional statements using null-aware

When using the ?? operator, if the left value is null, it returns the right value. It has the advantage of preventing errors that may occur by specifying a value when it is null.

String? name;
String greeting = name ?? "이름이 없습니다";
print(greeting);

function

As the widget tree grows deeper, Flutter suffers from maintenance and readability issues. To prevent this from happening, you need to create a function and separate it into functional units. You can create a fetchData() function to handle asynchronous operations like this: When handling asynchronous operations in Flutter, you use async and await. The return type uses Future to indicate asynchronous processing. It is an object that represents a value that will be completed in the future. Use Future.wait() to process it using multiple Futures and wait until all are completed.

Future<void> fetchData() async {
await Future.delayed(Duration(seconds: 2));
print("Data fetched!");
}

class

dart is an object-oriented language that uses classes as objects. You can use it to create a model for a user and define each property, as shown below, or to create an object model with functions that handle those properties.

class UserModel {
String name;
int age;
String status;
UserModel({required this.name, required this.age, this.status = '오프라인'});
void updateStatus(String newStatus) {
status = newStatus;
}
}

Generic

Code reusability can be increased with the ability to support various types by generalizing data types in classes or functions.

  • It is best to specify type parameters when creating an object. Otherwise, it may behave dynamic and lose type safety.
  • Excessive use of generics can complicate the code, so it is best to use them only when necessary.
class Box<T> {
T value;
Box(this.value);
void showType() {
print('Type of value: ${value.runtimeType}');
}
}
void main() {
var intBox = Box<int>(123);
intBox.showType(); // Type of value: int
var stringBox = Box<String>('Hello');
stringBox.showType(); // Type of value: String
}

Comments

  • Used when writing comments for collaboration or writing content about code I wrote.
  • //, /* */, /// (document comment, can be expressed in the same way as [a])

Functional programming

Also called method chaining, it refers to a method of connecting and using multiple functions. It is used when there are few state changes and data conversion-oriented tasks, when there is a lot of parallel processing or asynchronous work, and when code stability and readability are important. On the other hand, imperative programming is used to create prototypes intuitively and quickly, and the possibility of errors is relatively higher due to verbose code than functional programming. type conversion function

  • toString(), int.parse(''), double.parse(''), toList(), toSet(), asMap() higher order function
  • map(), where(), firstWhere(), lastWhere(), reduce(), fold(), any(), every(), takeWhile(), skipWhile()
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var evenNumbers = numbers.where((number) => number.isEven);
var result = evenNumbers.reduce((a, b) => a + b);
print(result); // 30

Object-oriented programming

It is efficient to create multiple objects of the same type by creating a class. Maintenance becomes easier by inheriting and reusing this class or defining methods in the class that can be used simultaneously by the corresponding objects.

class Animal {
String name;
int age;
Animal(this.name, this.age);
void speak() {
print('$name이(가) 소리를 냅니다!');
}
}
void main() {
var dog = Animal('멍멍이', 3);
var cat = Animal('야옹이', 2);
dog.speak();
cat.speak();
}

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164