Skip to content

Commit

Permalink
Format dart files and fix rebase mistake
Browse files Browse the repository at this point in the history
  • Loading branch information
kuhnroyal committed Oct 29, 2021
1 parent 2e273e6 commit 4973a4c
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 45 deletions.
95 changes: 71 additions & 24 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,31 +51,62 @@ class MyHomePage extends StatefulWidget with WidgetsBindingObserver {
class _MyHomePageState extends State<MyHomePage> {
bool wifiOnly = false;
final _documents = [
{'name': 'Learning Android Studio', 'link': 'http://barbra-coco.dyndns.org/student/learning_android_studio.pdf'},
{'name': 'Android Programming Cookbook', 'link': 'http://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-Programming-Cookbook.pdf'},
{'name': 'iOS Programming Guide', 'link': 'http://darwinlogic.com/uploads/education/iOS_Programming_Guide.pdf'},
{'name': 'Objective-C Programming (Pre-Course Workbook', 'link': 'https://www.bignerdranch.com/documents/objective-c-prereading-assignment.pdf'},
{
'name': 'Learning Android Studio',
'link':
'http://barbra-coco.dyndns.org/student/learning_android_studio.pdf'
},
{
'name': 'Android Programming Cookbook',
'link':
'http://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-Programming-Cookbook.pdf'
},
{
'name': 'iOS Programming Guide',
'link':
'http://darwinlogic.com/uploads/education/iOS_Programming_Guide.pdf'
},
{
'name': 'Objective-C Programming (Pre-Course Workbook',
'link':
'https://www.bignerdranch.com/documents/objective-c-prereading-assignment.pdf'
},
];

final _images = [
{
'name': 'Arches National Park',
'link': 'https://upload.wikimedia.org/wikipedia/commons/6/60/The_Organ_at_Arches_National_Park_Utah_Corrected.jpg'
'link':
'https://upload.wikimedia.org/wikipedia/commons/6/60/The_Organ_at_Arches_National_Park_Utah_Corrected.jpg'
},
{
'name': 'Canyonlands National Park',
'link': 'https://upload.wikimedia.org/wikipedia/commons/7/78/Canyonlands_National_Park%E2%80%A6Needles_area_%286294480744%29.jpg'
'link':
'https://upload.wikimedia.org/wikipedia/commons/7/78/Canyonlands_National_Park%E2%80%A6Needles_area_%286294480744%29.jpg'
},
{
'name': 'Death Valley National Park',
'link': 'https://upload.wikimedia.org/wikipedia/commons/b/b2/Sand_Dunes_in_Death_Valley_National_Park.jpg'
'link':
'https://upload.wikimedia.org/wikipedia/commons/b/b2/Sand_Dunes_in_Death_Valley_National_Park.jpg'
},
{'name': 'Gates of the Arctic National Park and Preserve', 'link': 'https://upload.wikimedia.org/wikipedia/commons/e/e4/GatesofArctic.jpg'}
{
'name': 'Gates of the Arctic National Park and Preserve',
'link':
'https://upload.wikimedia.org/wikipedia/commons/e/e4/GatesofArctic.jpg'
}
];

final _videos = [
{'name': 'Big Buck Bunny', 'link': 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'},
{'name': 'Elephant Dream', 'link': 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4'}
{
'name': 'Big Buck Bunny',
'link':
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
},
{
'name': 'Elephant Dream',
'link':
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4'
}
];

List<_TaskInfo>? _tasks;
Expand Down Expand Up @@ -106,7 +137,8 @@ class _MyHomePageState extends State<MyHomePage> {
}

void _bindBackgroundIsolate() {
bool isSuccess = IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
bool isSuccess = IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
if (!isSuccess) {
_unbindBackgroundIsolate();
_bindBackgroundIsolate();
Expand Down Expand Up @@ -134,11 +166,14 @@ class _MyHomePageState extends State<MyHomePage> {
IsolateNameServer.removePortNameMapping('downloader_send_port');
}

static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
static void downloadCallback(
String id, DownloadTaskStatus status, int progress) {
if (debug) {
print('Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
print(
'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
}
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
final SendPort send =
IsolateNameServer.lookupPortByName('downloader_send_port')!;
send.send([id, status, progress]);
}

Expand Down Expand Up @@ -188,7 +223,8 @@ class _MyHomePageState extends State<MyHomePage> {
onItemClick: (task) {
_openDownloadedFile(task).then((success) {
if (!success) {
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Cannot open this file')));
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Cannot open this file')));
}
});
},
Expand All @@ -214,7 +250,8 @@ class _MyHomePageState extends State<MyHomePage> {
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Text(
title,
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.blue, fontSize: 18.0),
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.blue, fontSize: 18.0),
),
);

Expand All @@ -241,7 +278,10 @@ class _MyHomePageState extends State<MyHomePage> {
},
child: Text(
'Retry',
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 20.0),
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 20.0),
))
],
),
Expand Down Expand Up @@ -299,15 +339,17 @@ class _MyHomePageState extends State<MyHomePage> {
}

void _delete(_TaskInfo task) async {
await FlutterDownloader.remove(taskId: task.taskId!, shouldDeleteContent: true);
await FlutterDownloader.remove(
taskId: task.taskId!, shouldDeleteContent: true);
await _prepare();
setState(() {});
}

Future<bool> _checkPermission() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
if (widget.platform == TargetPlatform.android && androidInfo.version.sdkInt <= 28) {
if (widget.platform == TargetPlatform.android &&
androidInfo.version.sdkInt <= 28) {
final status = await Permission.storage.status;
if (status != PermissionStatus.granted) {
final result = await Permission.storage.request();
Expand All @@ -330,23 +372,26 @@ class _MyHomePageState extends State<MyHomePage> {
_tasks = [];
_items = [];

_tasks!.addAll(_documents.map((document) => _TaskInfo(name: document['name'], link: document['link'])));
_tasks!.addAll(_documents.map((document) =>
_TaskInfo(name: document['name'], link: document['link'])));

_items.add(_ItemHolder(name: 'Documents'));
for (int i = count; i < _tasks!.length; i++) {
_items.add(_ItemHolder(name: _tasks![i].name, task: _tasks![i]));
count++;
}

_tasks!.addAll(_images.map((image) => _TaskInfo(name: image['name'], link: image['link'])));
_tasks!.addAll(_images
.map((image) => _TaskInfo(name: image['name'], link: image['link'])));

_items.add(_ItemHolder(name: 'Images'));
for (int i = count; i < _tasks!.length; i++) {
_items.add(_ItemHolder(name: _tasks![i].name, task: _tasks![i]));
count++;
}

_tasks!.addAll(_videos.map((video) => _TaskInfo(name: video['name'], link: video['link'])));
_tasks!.addAll(_videos
.map((video) => _TaskInfo(name: video['name'], link: video['link'])));

_items.add(_ItemHolder(name: 'Videos'));
for (int i = count; i < _tasks!.length; i++) {
Expand Down Expand Up @@ -394,7 +439,8 @@ class _MyHomePageState extends State<MyHomePage> {
externalStorageDirPath = directory?.path;
}
} else if (Platform.isIOS) {
externalStorageDirPath = (await getApplicationDocumentsDirectory()).absolute.path;
externalStorageDirPath =
(await getApplicationDocumentsDirectory()).absolute.path;
}
return externalStorageDirPath;
}
Expand Down Expand Up @@ -440,7 +486,8 @@ class DownloadItem extends StatelessWidget {
],
),
),
data!.task!.status == DownloadTaskStatus.running || data!.task!.status == DownloadTaskStatus.paused
data!.task!.status == DownloadTaskStatus.running ||
data!.task!.status == DownloadTaskStatus.paused
? Positioned(
left: 0.0,
right: 0.0,
Expand Down
54 changes: 33 additions & 21 deletions lib/src/downloader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import 'models.dart';
/// * `progress`: current progress value of a download task, the value is in
/// range of 0 and 100
///
typedef void DownloadCallback(String id, DownloadTaskStatus status, int progress);
typedef void DownloadCallback(
String id, DownloadTaskStatus status, int progress);

///
/// A convenient class wraps all api functions of **FlutterDownloader** plugin
Expand All @@ -26,12 +27,14 @@ class FlutterDownloader {
static bool _initialized = false;

static Future<Null> initialize({bool debug = true}) async {
assert(!_initialized, 'FlutterDownloader.initialize() must be called only once!');
assert(!_initialized,
'FlutterDownloader.initialize() must be called only once!');

WidgetsFlutterBinding.ensureInitialized();

final callback = PluginUtilities.getCallbackHandle(callbackDispatcher)!;
await _channel.invokeMethod('initialize', <dynamic>[callback.toRawHandle(), debug ? 1 : 0]);
await _channel.invokeMethod(
'initialize', <dynamic>[callback.toRawHandle(), debug ? 1 : 0]);
_initialized = true;
return null;
}
Expand Down Expand Up @@ -65,24 +68,27 @@ class FlutterDownloader {
///
/// an unique identifier of the new download task
///
static Future<String?> enqueue(
{required String url,
required String savedDir,
String? fileName,
Map<String, String>? headers,
bool showNotification = true,
bool openFileFromNotification = true,
bool requiresStorageNotLow = true,
bool saveInPublicStorage = false
bool allowCellular = true,
}) async {
static Future<String?> enqueue({
required String url,
required String savedDir,
String? fileName,
Map<String, String>? headers,
bool showNotification = true,
bool openFileFromNotification = true,
bool requiresStorageNotLow = true,
bool saveInPublicStorage = false,
bool allowCellular = true,
}) async {
assert(_initialized, 'FlutterDownloader.initialize() must be called first');
assert(Directory(savedDir).existsSync());

StringBuffer headerBuilder = StringBuffer();
if (headers != null) {
headerBuilder.write('{');
headerBuilder.writeAll(headers.entries.map((entry) => '\"${entry.key}\": \"${entry.value}\"'), ',');
headerBuilder.writeAll(
headers.entries
.map((entry) => '\"${entry.key}\": \"${entry.value}\"'),
',');
headerBuilder.write('}');
}
try {
Expand Down Expand Up @@ -152,11 +158,13 @@ class FlutterDownloader {
/// FlutterDownloader.loadTasksWithRawQuery(query: 'SELECT * FROM task WHERE status=3');
/// ```
///
static Future<List<DownloadTask>?> loadTasksWithRawQuery({required String query}) async {
static Future<List<DownloadTask>?> loadTasksWithRawQuery(
{required String query}) async {
assert(_initialized, 'FlutterDownloader.initialize() must be called first');

try {
List<dynamic> result = await _channel.invokeMethod('loadTasksWithRawQuery', {'query': query});
List<dynamic> result = await _channel
.invokeMethod('loadTasksWithRawQuery', {'query': query});
return result
.map((item) => new DownloadTask(
taskId: item['task_id'],
Expand Down Expand Up @@ -292,11 +300,13 @@ class FlutterDownloader {
/// * `shouldDeleteContent`: if the task is completed, set `true` to let the
/// plugin remove the downloaded file. The default value is `false`.
///
static Future<Null> remove({required String taskId, bool shouldDeleteContent = false}) async {
static Future<Null> remove(
{required String taskId, bool shouldDeleteContent = false}) async {
assert(_initialized, 'FlutterDownloader.initialize() must be called first');

try {
return await _channel.invokeMethod('remove', {'task_id': taskId, 'should_delete_content': shouldDeleteContent});
return await _channel.invokeMethod('remove',
{'task_id': taskId, 'should_delete_content': shouldDeleteContent});
} on PlatformException catch (e) {
print(e.message);
return null;
Expand Down Expand Up @@ -388,7 +398,9 @@ class FlutterDownloader {
assert(_initialized, 'FlutterDownloader.initialize() must be called first');

final callbackHandle = PluginUtilities.getCallbackHandle(callback)!;
assert(callbackHandle != null, 'callback must be a top-level or a static function');
_channel.invokeMethod('registerCallback', <dynamic>[callbackHandle.toRawHandle()]);
assert(callbackHandle != null,
'callback must be a top-level or a static function');
_channel.invokeMethod(
'registerCallback', <dynamic>[callbackHandle.toRawHandle()]);
}
}

0 comments on commit 4973a4c

Please sign in to comment.