TIL #012
191118 월
오늘 배운 점
<Flutter>
1. video_player - 영상 재생하기
- 앱에 영상 재생 기능도 추가돼야 할 것 같다는 의견이 나와서 이런 플러그인을 발견했다.
//@pubspec.yaml
dependencies:
flutter:
sdk: flutter
video_player:
//permissions
//AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application ...>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
//Info.plist for iOS
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController _controller; //컨트롤러 필요
Future<void> _initializeVideoPlayerFuture; //저장할 Future 필요
@override
void initState() {
//VideoPlayerController 생성 및 저장
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
);
_initializeVideoPlayerFuture = _controller.initialize();
_controller.setLooping(true); //영상 다시 재생
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return AspectRatio(//영상의 비율을 맞추기 위해 aspectRatio로 감싸줌
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller), //영상을 화면에 구현
);
} else {//아직 초기화중이면 로딩 화면 표시
return Center(child: CircularProgressIndicator());
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {//setState로 감싸서 상태에 따라 icon이 반영되도록 함
if (_controller.value.isPlaying) {//재생중이라면 일시정지
_controller.pause();
} else {//일시정지중이라면 재생
_controller.play();
}
});
},
//player 상태에 따른 icon 표시
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
);
}
}
- 이런 업로드 플러그인도 있는데, 사전 설정 작업만 해도 엄청나게 까다로워 보인다.. 하하https://pub.dev/packages/flutter_uploader
2. Notification 핸들링
//@pubspec.yaml
dependencies:
flutter:
sdk: flutter
cupertino_icons:
flutter_calendar:
shared_preferences:
flutter_launcher_icons:
flutter_local_notifications:
@AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
//초기화 작업
var _flutterLocalNotificationsPlugin;
void initState() {
super.initState();
var androidSetting = AndroidInitializationSettings('@mipmap/ic_launcher');//디폴트 아이콘
//다른 이미지 사용하려면 android drawable 폴더에 이미지를 넣어 사용
var initializationSettings = InitializationSettings(androidSetting, iosSetting);
_flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
_flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
//callback 등록. 알람 선택시 실행할 기능 정의할 수 있다
Future onSelectNotification(String payload) async {
//예시로 notification 클릭시 payload 보여주는 다이얼로그 보여줌
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Notification Payload'),
content: Text('Payload: $payload'),
),
);
}
Future _showNotificationWithSound() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel id', 'channel name', 'channel description',
sound: 'slow_spring_board',
importance: Importance.Max,
priority: Priority.High
);
var iosPlatformChannelSpecifics = IOSNotificationDetails(sound: 'slow_spring_board.aiff');
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iosPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.show(
0,
'Simple Notification',
'내용',
platformChannelSpecifics,
payload: 'Hello Flutter',
);
}
Future _showNotificationRepeat() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel id', 'channel name', 'channel description',
sound: 'slow_spring_board',
importance: Importance.Max,
priority: Priority.High
);
var iosPlatformChannelSpecifics = IOSNotificationDetails(sound: 'slow_spring_board.aiff');
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iosPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.periodicallyshow(
1,
'Repeat Notification',
'내용',
RepeatInterval.EveryMinute,//1분마다 notification 호출
//Enum으로 Hourly, Daily, Weekly도 가능
platformChannelSpecifics,
payload: 'Hello Flutter',
);
}
Future _showNotificationAtTime() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel id', 'channel name', 'channel description',
sound: 'slow_spring_board',
importance: Importance.Max,
priority: Priority.High
);
var iosPlatformChannelSpecifics = IOSNotificationDetails(sound: 'slow_spring_board.aiff');
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iosPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.schedule(
1,
'Scheduled Notification',
'내용',
DateTime.now().add(Duration(seconds: 5)),
platformChannelSpecifics,
payload: 'Hello Flutter',
);
}
@override //display 빌드는 이런식으로 한다.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('Simple Notification'),
onPressed: _showNotificationWithSound,
),
RaisedButton(
child: Text('Repeat Notification'),
onPressed: _showNotificationRepeat,
),
RaisedButton(
child: Text('Scheduled Notification'),
onPressed: _showNotificationAtTime,
),
RaisedButton(
child: Text('취소'),
onPressed: () => _flutterLocalNotificationsPlugin.cancelAll(),
),
],
),
),
);
}
}
내일 배울 점
1. 당장의 과제와 레포트를 해낸다,,
더보기
- 바빠도 1가지 기능씩은 공부할 예정이다.
- 바빠도 1가지 기능씩은 공부할 예정이다.
'삽질하는 개발자 hashblown' 카테고리의 다른 글
프론트엔드 개발자의 TIL #014 (0) | 2019.11.21 |
---|---|
프론트엔드 개발자의 TIL #013 (0) | 2019.11.20 |
프론트엔드 개발자의 TIL #011 (0) | 2019.11.16 |
프론트엔드 개발자의 TIL #010 (0) | 2019.11.13 |
프론트엔드 개발자의 TIL #009 (0) | 2019.11.12 |
댓글