본문 바로가기
  • GDG on campus Ewha Tech Blog
3-2기 스터디/플러터

[7주차] 튜토리얼 영상 #23-26

by vitaminmin 2022. 6. 25.

이번 7주차는 플러터 스터디의 마지막 주차로, 튜토리얼 영상 #23-26을 학습하였습니다.


#23- Maps & Routing

Map 개념 이해하기:

void main(){

	Map student = {'name': 'chun-li', 'age': 25};
	print(student['name']);

}

//result: chun-li

 

→ Routes can be created using 'Map'

 

Routing→ Stack처럼 쌓이는 개념! route를 pop, push 하는 것.

-Navigator.push()

-Navigator.pop()

그래서 효율적으로 이 route를 관리하는 것이 중요.

 

main.dart

void main() => runApp(MaterialApp(
    initialRoute: '/home',
    routes: {
      '/': (context) => Loading(),
      '/home': (context) => Home(),
      '/location': (context) => ChooseLocation(),
    }
));

 

loading.dart

class Loading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('loading screen'),
    );
  }
}

 

home.dart

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            FlatButton.icon(
              onPressed: () {
                Navigator.pushNamed(context, '/location'); //push
              },
              icon: Icon(Icons.edit_location),
              label: Text(
                'Edit Location'
              )
            )
          ],
        ),
      ),
    );
  }
}

 

 

choose_location.dart

class _ChooseLocationState extends State<ChooseLocation> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: Text('Choose a Location'),
        centerTitle: true,
        elevation: 0,
      ),
    );
  }
}

 

Route 관련 Flutter 공식 문서 링크: https://flutter-ko.dev/docs/cookbook/navigation/navigation-basics

 

새로운 화면으로 이동하고, 되돌아오기

화면간 이동하는 방법

flutter-ko.dev


#24 - Widget Lifecycle

 

Stateless vs Stateful:

Stateless

-State does not change over time

-build function only runs once

Stateful

-State CAN change over time

-setState() triggers the build function

 

initState()

-called only once when the widget is created

-subscribe to streams or any object that could change our widget data

 

build()

-builds the widget tree

-a build is triggered every time we use setState()

 

Dispose()

-when the widget/state object is removed

 

choose_location.dart

class ChooseLocation extends StatefulWidget {
  @override
  _ChooseLocationState createState() => _ChooseLocationState();
}

class _ChooseLocationState extends State<ChooseLocation> {

  int counter = 0;

  @override
  void initState() {
    super.initState();
    print('initState function ran');
  }

  @override
  Widget build(BuildContext context) {
    print('build function ran');
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: Text('Choose a Location'),
        centerTitle: true,
        elevation: 0,
      ),
      body: RaisedButton(
        onPressed: (){
          setState(() {
            counter += 1;
          });
        },
        child: Text('$counter'),
      )
    );
  }
}

 


#25 - Asynchronous Code

Asynchronous(비동기) code:

  • represents an action that starts now and finishes sometime in the future
    (ex. Interacting with an API endpoint to get some data)
  • starts through request but it doesn’t finish straight away, rather it finishes sometime later
    (In the meantime, our code should not stop until that request is complete)
  • should be non-blocking (rest of the codes should carry on)

 

비동기 처리를 위한 'Future'

 

choose_location.dart

class _ChooseLocationState extends State<ChooseLocation> {

  void getData() async {

    // simulate network request for a username
    String username = await Future.delayed(Duration(seconds: 3), () {
      return 'yoshi';
    });

    // simulate a network request to get the bio of that username
    String bio = await Future.delayed(Duration(seconds: 2), () {
      return 'vegan, musician & egg collector';
    });

    print('$username - $bio');

  }

  @override
  void initState() {
    super.initState();
    getData();
    print('hey there!');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: Text('Choose a Location'),
        centerTitle: true,
        elevation: 0,
      ),
    );
  }
}

 


#26 - Flutter Packages (http)

 

pub.dev 웹사이트에 접속하여, flutter 패키지를 검색한다:
https://pub.dev/packages?q=sdk%3Aflutter

 

Search results for sdk:flutter.

Pub is the package manager for the Dart programming language, containing reusable libraries & packages for Flutter, AngularDart, and general Dart programs.

pub.dev

 

Dart의 http package를 Dependencies에 추가한다 → Get Dependencies 클릭하여 변경 사항을 반영한다.

dependencies:
  http: ^0.13.4

 

cf) Dart의 http package 공식 링크: https://pub.dev/packages/http

 

http | Dart Package

A composable, multi-platform, Future-based API for HTTP requests.

pub.dev

 

JSONPlaceholder를 활용하여 테스트를 한다.

http://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.

jsonplaceholder.typicode.com

 

loading.dart

class Loading extends StatefulWidget {
  @override
  _LoadingState createState() => _LoadingState();
}

class _LoadingState extends State<Loading> {

  void getData() async {

    Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
    // print(response.body);
    Map data = jsonDecode(response.body); //this converts the json format into the data that we can work with  
    print(data);
    print(data['title']);
//result: delectus aut autem

  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('loading screen'),
    );
  }
}

 

jsonDecode: converts the json format into the data that we can work with


총 7주라는 시간동안, 플러터 스터디에서는 튜토리얼 영상 #1-26을 통해 플러터 기본 개념 전반에 대해 함께 공부해보는 시간을 가졌습니다.

스터디에서 함께 공부한 내용을 바탕으로 미래에 멋진 프로젝트를 하게 될 부원들을 기대해주세요~

지금까지 플러터 스터디였습니다, 감사합니다!

댓글