본문 바로가기
Tech/flutter

[flutter] favorites 공략 - url_launcher 패키지 파헤쳐보기

by 패드로 2020. 10. 29.
 

[flutter] 플러터 공부좀 해봤다면 flutter favorites는 써봐야지

Flutter 공부를 하다보면 본인이 만든 패키지를 쓰기도 하지만 다른 기관 / 팀 / 사람들이 만들어둔 패키지를 사용하기도 합니다. 애초에 플러터가 레고 형식으로 간단히 조립해서 사용하기 좋은

padro.tistory.com

flutter favorites 패키지 한번씩 써보기 1탄으로 현재 핸드폰의 인터넷 연결 상태를 반환하는 Connectivity 패키지를 간단하게 적용해보겠습니다.

 

패키지 주소: pub.dev/packages/url_launcher

 

url_launcher | Flutter Package

Flutter plugin for launching a URL on Android and iOS. Supports web, phone, SMS, and email schemes.

pub.dev

1436개의 좋아요, Pub points 110점, 인지도 100%의 패키지며, 플러터 팀에 의해 배포된 패키지입니다.

설치법은 위의 패키지 사이트에 잘 나와있고 여기 적어도 곧 업데이트 되면 바뀔 것이기 때문에 위 링크를 참고해주세요.

 

사용법은 매우 간단합니다. 그냥 url 넣고 실행시키면 끝!(?)

url을 넣기 전에 canLaunch(url) 형식으로 실행시킬 수 있는 url인지 한번 검증을 한 후 launch(url)을 해주면 끝입니다.

 

if (await canLaunch(url)) {
    await launch(url);

    //url 실행
} else {
    throw 'Could not launch $url';

    //예외처리
}

 

사용을 위해 간단한 클래스 하나를 만들었습니다.

길어보이지만 그냥 이메일, 문자, 전화 url을 만든 후 실행하는 함수를 적은 것 뿐입니다.

이메일의 경우 보기좋게 Uri 기능을 써서 메일 제목과 내용까지 넣어준 것과 Uri를 썼기 때문에 toString()을 통해 launch의 파라미터로 작동할 수 있도록 변환만 해주었습니다.

 

이 기능은 메뉴 화면에서 개발자 연락처 클릭하면 작동하도록 코딩할 예정입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import 'dart:core';
 
import 'package:url_launcher/url_launcher.dart';
 
class UrlLauncher {
  final Uri EMAIL = Uri(
      scheme: 'mailto',
      path: 'jaesungdev@gmail.com',
      queryParameters: {'subject''문의 드립니다''body''개발자님 안녕하세요?'});
  static const CALL = 'tel:01080805801';
  static const SMS = 'sms:01080805801';
 
  void launchURL(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
 
  void call() async {
    if (await canLaunch(CALL)) {
      await launch(CALL);
    } else {
      throw 'error call';
    }
  }
 
  void sms() async {
    if (await canLaunch(SMS)) {
      await launch(SMS);
    } else {
      throw 'error sms';
    }
  }
 
  void email() async {
    if (await canLaunch(EMAIL.toString())) {
      await launch(EMAIL.toString());
    } else {
      throw 'error email';
    }
  }
}
 
cs

자 이제 이부분을 제 Drawer에다가 개발자 연락하기 옵션으로 넣을 생각입니다.

DeveloperContact라는 위젯을 만든 후 제 Drawer(메뉴)에 적용시켰습니다.

두줄에 나눠서 버튼 2개씩 나눠지게 정렬해두었고, 마지막에 블로그 연결을 launchUrl 메소드로 연결하여 실행해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import 'package:accidentv/helper/url_launcher.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
 
class DeveloperContact extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          height: 20,
        ),
        Divider(
          color: Colors.grey,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            RaisedButton.icon(
                color: Colors.redAccent,
                onPressed: UrlLauncher().email,
                icon: Icon(Icons.email),
                label: Text('mail')),
            RaisedButton.icon(
                color: Colors.redAccent,
                onPressed: UrlLauncher().call,
                icon: Icon(Icons.phone),
                label: Text('call')),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            RaisedButton.icon(
                color: Colors.redAccent,
                onPressed: UrlLauncher().sms,
                icon: Icon(Icons.sms),
                label: Text('sms')),
            RaisedButton.icon(
                color: Colors.redAccent,
                onPressed: () {
                  UrlLauncher().launchURL("https://padro.tistory"
                      ".com");
                },
                icon: Icon(Icons.web),
                label: Text('blog')),
          ],
        )
      ],
    );
  }
}
 
cs

잘 작동하는지 볼까요?

 

전화, 문자, 메일, 외부블로그 모두 잘 작동하는 것을 확인 할 수 있습니다!

 

댓글