📱 Mobile/📱 (old) Flutter v 1.0

외부 라이브러리 사용

DarrenKwonDev 2020. 5. 14. 14:12

node.js에는 package.json, python에는 requirements.txt가 있듯, Flutter에서는 pubspec.yaml을 사용한다.

패키지 문서는 npm, pypi를 찾아보듯 dart.env에서 찾아본다.

 

image picker라는 것을 이용해봄으로써 flutter 환경에서 라이브러리를 설치하고 활용해보자.

 

 

image_picker | Flutter Package

Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera.

pub.dev

 

🚀 설치

 

pubspec.yaml에 다음을 붙여 넣기 한다.

dependencies:
  image_picker: ^0.6.6+1

 

그 후에야 flutter pub get 명령어를 통해 설치할 수 있게 된다.

 

설치를 마친 후에는 import하여 활용하자.

import 'package:image_picker/image_picker.dart';

 

참고로, 외부 패키지를 설치했다면 에뮬을 재시작해야 반영이 된다.

 

 

 

🚀 활용

 

공식 문서의 활용 예시를 보며 활용할 수 있다.

 

Future와 async/await가 일부 쓰였다. Future는 JS의 Promise와 같은 것이다.

# 공식 문서 예시에는 없는데 dart:io를 import해줘야 한다.
import 'dart:io';
import 'package:image_picker/image_picker.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  // File인 _image 변수 설정
  File _image;

  // 이미지를 가져오는 함수. 비동기 처리이므로 Future 형이고, async/await를 활용한다.
  Future getImage() async {
    // imagePicker의 pickImage 함수를 이용한다. (소스는 카메라, 갤러리 등 다양하니 원하는 대로)
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

	// 이미지는 바뀔 수 있으니 state로 바꿔준다.
    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        // 이미지가 있으면 Image 위젯을 이용해 보여준다.
        child: _image == null
            ? Text('No image selected.')
            : Image.file(_image),
      ),
      // 플로팅 액션 버튼을 누르면 getImage 함수를 실행한다.
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}

 

 

 


 

자주 쓰는 라이브러리

 

 

flutter_signin_button | Flutter Package

A Flutter plugin for iOS and Android for generating signin buttons for different social media account.

pub.dev

 

image_picker | Flutter Package

Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera.

pub.dev