플러터(Dart) 체크리스트

기본적인 Dart 언어 구조에 대해 설명했습니다.

Page content

다음은 Flutter (Dart)에 대한 참고표로, 가장 유용한 명령어와 언어 구조를 포함하고 있습니다:

개발자가 플루트와 다트를 연주하는 모습 위 이미지는 AI 생성 이미지 (Flux 1 dev 모델에 의해 생성됨)로, 개발자가 플루트와 다트를 연주하는 모습을 보여줍니다.

Flutter CLI 명령어

새로운 Flutter 프로젝트 생성:

flutter create <project_name>

Flutter 앱 실행:

flutter run

릴리스 APK 빌드:

flutter build apk

Dart 코드 분석:

flutter analyze

테스트 실행:

flutter test

패키지 설치:

flutter pub get

Flutter 업그레이드:

flutter upgrade

Flutter 설치 확인:

flutter doctor

Dart 언어 구조

변수와 데이터 타입:

int age = 30;
double price = 9.99;
String name = 'John';
bool isActive = true;
var dynamicVar = 'Can be any type';
final constantVar = 'Cannot be reassigned';
const compiletimeConstant = 'Compile-time constant';

Null Safety:

String? nullableString;
String nonNullableString = 'Hello';

함수:

void simplePrint() {
  print('Hello');
}

int add(int a, int b) => a + b;

void namedParams({required String name, int? age}) {
  // 함수 본문
}

void optionalParams(String name, [int? age]) {
  // 함수 본문
}

제어 흐름:

if (condition) {
  // 코드
} else if (anotherCondition) {
  // 코드
} else {
  // 코드
}

for (var i = 0; i < 5; i++) {
  // 코드
}

while (condition) {
  // 코드
}

switch (variable) {
  case value1:
    // 코드
    break;
  default:
    // 코드
}

리스트와 맵:

List<int> numbers = [1, 2, 3];
Map<String, int> ages = {'Alice': 30, 'Bob': 25};

클래스:

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  void sayHello() {
    print('Hello, I am $name');
  }
}

비동기 프로그래밍:

Future<void> fetchData() async {
  try {
    var result = await someAsyncOperation();
    print(result);
  } catch (e) {
    print('Error: $e');
  }
}

스트림:

Stream<int> countStream(int max) async* {
  for (int i = 0; i < max; i++) {
    yield i;
  }
}

에러 처리:

try {
  // 예외가 발생할 수 있는 코드
} on SpecificException {
  // 특정 예외 처리
} catch (e) {
  // 모든 예외 처리
} finally {
  // 항상 실행
}

이 참고표는 Flutter 개발자들이 빠르게 참조할 수 있도록 Flutter의 가장 중요한 명령어와 Dart 언어 구조를 다룹니다.

Flutter / Dart에서의 Null Safety

Flutter 앱에서 Dart로 Null Safety를 처리하는 것은 견고하고 오류 없는 코드를 작성하는 데 매우 중요합니다. Null Safety를 사용하는 방법에 대한 간단한 가이드를 아래에 제시합니다:

변수 선언

비가능한 변수:

int age = 30;
String name = 'John';

가능한 변수:

int? nullableAge;
String? nullableName;

가능한 타입과 작업

Null-aware 연산자:

  1. Null-aware 접근 연산자 (?.)
String? name;
print(name?.length); // name이 null이 아닐 경우 길이를 안전하게 접근
  1. Null-coalescing 연산자 (??)
String? name;
String displayName = name ?? 'Guest';
  1. Null-aware 할당 연산자 (??=)
String? name;
name ??= 'John'; // name이 null일 경우 'John'을 할당

Null assertion 연산자 (!) 이 연산자는 주의 깊게 사용해야 하며, 값이 null일 경우 런타임 오류로 이어질 수 있습니다:

String? nullableName = 'John';
String nonNullableName = nullableName!;

흐름 분석

Dart의 흐름 분석은 nullable 변수가 안전하게 사용될 수 있는 시점을 결정해줍니다:

String? getName() => 'John';

void printName() {
  String? name = getName();
  if (name != null) {
    print(name.length); // 여기서 name을 안전하게 사용할 수 있음
  }
}

late 변수

선언 후 초기화되는 비가능한 변수에 late를 사용합니다:

late String lateInitializedName;
void initializeName() {
  lateInitializedName = 'John';
}

nullable 파라미터 처리

void greet(String name, {String? title}) {
  if (title != null) {
    print('Hello, $title $name');
  } else {
    print('Hello, $name');
  }
}

컬렉션 작업

nullable 리스트:

List<String>? nullableList;
List<String?> listOfNullableStrings = ['Hello', null, 'World'];

null 값 필터링:

List<String?> mixedList = ['a', null, 'b', null, 'c'];
List<String> nonNullList = mixedList.whereType<String>().toList();

이러한 실천을 따르면 Dart 및 Flutter 앱에서 Null Safety를 효과적으로 처리할 수 있으며, null 관련 오류의 위험을 줄이고 전체적인 코드 품질을 향상시킬 수 있습니다.

유용한 링크