반응형
// 이곳에 쓴 내용은 앱 만들기라는 버킷리스트를 달성하기 위해 플러터를 공부하면서 정리하고 있는 내용입니다.
플러터에 대해 아는 것이 거의 없기 때문에 정리하면서 오류가 있을 수 있습니다.
오류를 발견하신 분은 댓글 남겨 주시면 감사하겠습니다.
이미지 파일 내려받기
The official repository for Dart and Flutter packages.
Pub is the package manager for the Dart programming language, containing reusable libraries & packages for Flutter and general Dart programs.
pub.dev
에서 dio, path_provider, http를 검색해서 최신 버전을 확인하고, pubspec.yaml파일에 추가한 후, Pub get~!
그리고, 깃허브에 올라온 거 보고 한글타자연습.. (코드타자 연습이라고 해야 맞나?^^;;)
오늘은 이미지 파일을 내려 받고, 내려 받는 중 과정을 애니메이션?으로 보여주는 로딩과정을 보여주는 코스다.
main 다트 파일 코드
import 'package:flutter/material.dart';
import 'largeFileMain.dart';
void main(){
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const LargeFileMain(),
);
}
}
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
class LargeFileMain extends StatefulWidget {
const LargeFileMain({super.key});
@override
State<StatefulWidget> createState() => _LargeFileMain();
}
class _LargeFileMain extends State<LargeFileMain> {
bool downloading = false;
var progressString = "";
String? file = "";
TextEditingController? _editingController;
@override
void initState() {
super.initState();
_editingController = TextEditingController(
text: 'https://www.motherjones.com/wp-content/uploads/2019/12/Getty121719.jpg?w=1200&h=630&crop=1');
}
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(
_editingController!.value.text, '${dir.path}/myimage.jpg',
onReceiveProgress: (rec, total) {
print('Rec: $rec, Total: $total');
file = '${dir.path}/myimage.jpg';
setState(() {
downloading = true;
progressString = '${((rec / total) * 100).toStringAsFixed(0)}%';
});
});
} catch (e) {
print(e);
}
setState(() {
downloading = false;
progressString = 'Completed';
});
print('Download completed');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
controller: _editingController,
style: const TextStyle(color: Colors.white),
keyboardType: TextInputType.text,
decoration: const InputDecoration(hintText: 'url 입력하세요'),
),
),
body: Center(
child: downloading
? SizedBox(
height: 120,
width: 200,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const CircularProgressIndicator(),
const SizedBox(
height: 20,
),
Text(
'Downloading File: $progressString',
style: const TextStyle(
color: Colors.white,
),
)
],
),
),
)
: FutureBuilder(
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
print('none');
return const Text('데이터 없음');
case ConnectionState.waiting:
print('waiting');
return const CircularProgressIndicator();
case ConnectionState.active:
print('active');
return const CircularProgressIndicator();
case ConnectionState.done:
print('done');
if(snapshot.hasData){
return snapshot.data as Widget;
}
}
return const Text('데이터 없음');
},
future: downloadWidget(file!),
)),
floatingActionButton: FloatingActionButton(
onPressed: (){
downloadFile();
},
child: const Icon(Icons.file_download),
),
);
}
Future<Widget> downloadWidget(String filePath) async{
File file = File(filePath);
bool exist = await file.exists();
FileImage(file).evict();
if (exist) {
return Center(
child: Column(
children: <Widget>[Image.file(file)],
),
);
} else {
return const Text('No Data');
}
}
}
여러 번의 오류 수정을 통해 작동을 하게 되었다.ㅜ.ㅜ
아직도 멀었다. 코드타자연습이 아직도 힘들다. 이런데, 개발은 언제쯤 가능할는지..
반응형