🕊 Flutter/강의

주사위 어플 만들기

놀러와요 버그의 숲 2022. 4. 8. 06:21
728x90
반응형

우선, 처음 main.dart 파일안에 들어가는 파일은 다음과 같다. 

import 'package:flutter/material.dart';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Text('Dicee'),
          backgroundColor: Colors.red,
        ),
        body: DicePage(),
      ),
    ),
  );
}

class DicePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

처음 알았다. body: DicePage() 이런식으로 하면 body안에 저 내용이 들어 간다는 것을!! 

 

 

 

맥 기준 자동정렬 

cmd + option + L 

(쉼표 찍으면 알아서 자동정렬 )

 

 

 

이미지 불러오기 

그런데, 이미지가 스크린을 초과하는 문제가 발생했다! 

 

 

 

Expanded 써보기 

 

이를 해결하는 방법 두가지가 있는데 

1. 개별로 width를 정해주는 법

2. Expanded를 쓰는 법 

 

1번은 너무 하드코딩이기에, 2번 방법을 쓰겠다. 

 

이미지가 잘 나온 것을 확인 할 수 있다. 

 

 

 

Expanded 두개 만들고 flex 써보기 

 

자동으로 Expanded를 두개 넣어주면 알아서 크기 맞춰주고, flex를 2,1 이렇게 배분하면 앞에 것이 2배 커진다. 

이것은 비율인 것을 기억해라. 기본값은 flex:1로 다 설정이 되어있다. 

 

 

 

Image.asset('경로') 사용하기 

훨씬 코드가 간결해졌다. 뒤에것도 마찬가지로 바꾸어주자. 

 

 

 

만약 위젯 하나만 제거하고 싶다면? 

 

 

각 주사위에 Padding 넣어주기 

 

그럼 자동으로 padding이 감싸진다. padding은 16px을 주기로 했다

 

 

TextButton쓰기 

 

TextButton은 onPressed라는 인자가 꼭 들어가야한다. 이는 void callback이 들어가야한다.  => (){}

또한 child도 꼭 있어야 하는데 왜냐하면 버튼을 하려면 크기를 가늠해야하기 때문이다. 

이걸로 감싸면 자동 패딩이 있끼 때문에 원래있던 패딩 값은 빼주자. 

 

 

버튼 눌렀을 때 print 해보기 

자바스크립트의 console.log랑 비슷한것 같다. print(); 로 해준다. 

 

변수 사용해보기 

 

변수 쓴다음에 hot reload에 꼭 반영하려면 build문 안에다 적용해주어야 한다. 

변수를 가져다 쓸 때는 $표시를 반드시 써준다. 

 

 

StatefulWidget으로 변경 

 

import 'package:flutter/material.dart';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Text('Dicee'),
          backgroundColor: Colors.red,
        ),
        body: DicePage(),
      ),
    ),
  );
}

class DicePage extends StatefulWidget {
  const DicePage({Key? key}) : super(key: key);

  @override
  State<DicePage> createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  @override
  Widget build(BuildContext context) {
    var leftDiceNumber =4;

    return Center(
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextButton(
              onPressed: () {
                print('left button is pressed');
              },
              child: Image.asset('images/dice$leftDiceNumber.png'),
            ),
          ),
          Expanded(
            child: TextButton(
              onPressed: () {
                print('right button pressed');
              },
              child: Image.asset('images/dice1.png'),
            ),
          ),
        ],
      ),
    );
  }
}

그대로 복사해서 밑의 구문안에다가 넣어주었다. 

class _DicePageState extends State<DicePage>{}

 

 

setState 사용해보기 

 

주의해야할 점은 변수는 build보다 상위에 해야 적용된다는 점이다. 

setState를 통해서 어떤 상태가 변했는지를 감지하고 새롭게 UI를 업데이트 해준다. 

 

 

랜덤 숫자 만들어주기 

 

랜덤숫자를 만들어주려면 math라는 라이브러리를 import 해야한다.

import 'dart:math';

https://api.flutter.dev/flutter/dart-math/dart-math-library.html

 

dart:math library - Dart API

Mathematical constants and functions, plus a random number generator. To use this library in your code: import 'dart:math'; Random Random is a generator of bool, int or double values. var intValue = Random().nextInt(10); // Value is >= 0.0 and < 1.0. var d

api.flutter.dev

nextInt()같은 경우 괄호안에 최댓값이 들어간다. 예를들어 6이면 6보다 작은 5까지 되고 우리는 주사위 6이 필요하니까

+1을 더 해주어야한다. 

https://api.flutter.dev/flutter/dart-math/Random/nextInt.html

 

nextInt method - Random class - dart:math library - Dart API

int nextInt(int max ) Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive. Implementation note: The default implementation supports max values between 1 and (1<<32) inclusive. Implementation int n

api.flutter.dev