[Do it! 플러터] 도전! 다트 프로그램 만들어보기

Heeyoung Joe·2023년 11월 4일
0

Flutter

목록 보기
3/7
  • 구구단 프로그램 만들기,
  • 자동차 클래스 구현하기,
  • 로또 번호 생성기 만들기

총 3가지의 코드가 제공된 챕터이다.
각각 따라해보고, 몰랐던 것 적어보고 이걸 활용해서 9개의 자동차를 자동으로 만들어서 저장해주고, 보여줄 수 있는 프로그램으로 변형해보려고 한다.

후후 오류

void main() {
  Car bmw = Car(320, 100000, 'BMW');
  Car benz = Car(250, 70000, 'BENZ');
  Car ford = Car(200, 80000, 'FORD');
  bmw.saleCar();
  bmw.saleCar();
  bmw.saleCar();
  print(bmw.price);
}  
class Car {
  int maxSpeed;
  num price;
  String name;
  
  Car(int maxSpeed, num price, String name) {
    this.maxSpeed = maxSpeed;
    this.price = price;
    this.name = name;
  }
  
  num saleCar() {
    price = price * 0.9;
    return price;
  }
}

이 코드는 본디 72900.0의 결과가 나와야 하는데, 실행조차 되지 않는다.
에러의 내용은 아래와 같다.

Non-nullable instance field 'maxSpeed' must be initialized.

maxSpeed 뿐만 아니라 price와 name에도 같은 에러를 볼 수 있다.

해결 방법은 선언시 앞에 late 명령어를 붙여주거나 데이터타입에 ?를 붙여서 변수를 nullable로 바꾸는 것이다.

주의

주의할 것이 nullable한 변수에는 사칙연산이 불가하다. late을 붙여주는 것이 낫다.

좀 신기했던 점이라면 생성자를 만들 때는 this.를 꼭 붙여줘야 했으나 클래스 함수를 만들 때는 this. 없이 클래스 변수를 참조할 수 있다는 점이었다.

찐 도전

import 'dart:math' as math;

void main() {
  var rand = math.Random();
  List<String> car_names = ['BMW','FORD','BENZ'];
  List<Car> cars = [];
  for (int i = 0; i < 10; i ++) {
    cars.add(Car(rand.nextInt(100),car_names[rand.nextInt(3)]));
    cars[i].printInfo();
  }
  
}

class Car {
  late num price;
  String? name;
  
  Car(num price, String name) {
    this.price = price;
    this.name = name;
  }
  
  void printInfo() {
    print("This car is $name with price $price");
  }
}

결과

This car is FORD with price 97
This car is BMW with price 80
This car is FORD with price 63
This car is BENZ with price 93
This car is BENZ with price 23
This car is FORD with price 6
This car is BMW with price 22
profile
SW Engineer

0개의 댓글