-
-
Notifications
You must be signed in to change notification settings - Fork 457
/
locally_available_builder.dart
112 lines (102 loc) · 3.08 KB
/
locally_available_builder.dart
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
///
/// [Author] Alex (https://github.com/AlexV525)
/// [Date] 2021/7/23 16:07
///
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../constants/extensions.dart';
import '../scale_text.dart';
class LocallyAvailableBuilder extends StatefulWidget {
const LocallyAvailableBuilder({
Key? key,
required this.asset,
required this.builder,
this.isOriginal = true,
}) : super(key: key);
final AssetEntity asset;
final Widget Function(BuildContext context, AssetEntity asset) builder;
final bool isOriginal;
@override
_LocallyAvailableBuilderState createState() =>
_LocallyAvailableBuilderState();
}
class _LocallyAvailableBuilderState extends State<LocallyAvailableBuilder> {
bool _isLocallyAvailable = false;
PMProgressHandler? _progressHandler;
File? file;
@override
void initState() {
super.initState();
_checkLocallyAvailable();
}
Future<void> _checkLocallyAvailable() async {
_isLocallyAvailable = await widget.asset.isLocallyAvailable;
if (!mounted) {
return;
}
setState(() {});
if (!_isLocallyAvailable) {
_progressHandler = PMProgressHandler();
widget.asset
.loadFile(
progressHandler: _progressHandler,
isOrigin: widget.isOriginal,
)
.then((File? f) => file = f);
}
_progressHandler?.stream.listen((PMProgressState s) {
if (s.state == PMRequestState.success) {
_isLocallyAvailable = true;
file = null;
if (mounted) {
setState(() {});
}
}
});
}
Widget _indicator(BuildContext context) {
return StreamBuilder<PMProgressState>(
stream: _progressHandler!.stream,
initialData: const PMProgressState(0, PMRequestState.prepare),
builder: (BuildContext c, AsyncSnapshot<PMProgressState> s) {
if (s.hasData) {
final double progress = s.data!.progress;
final PMRequestState state = s.data!.state;
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
state == PMRequestState.failed
? Icons.cloud_off
: Icons.cloud_queue,
color: context.themeData.iconTheme.color?.withOpacity(.4),
size: 28,
),
if (state != PMRequestState.success &&
state != PMRequestState.failed)
ScaleText(
' iCloud ${(progress * 100).toInt()}%',
style: TextStyle(
color: context.themeData.textTheme.bodyText2?.color
?.withOpacity(.4),
),
),
],
);
}
return const SizedBox.shrink();
},
);
}
@override
Widget build(BuildContext context) {
if (_isLocallyAvailable) {
return widget.builder(context, widget.asset);
}
if (_progressHandler != null) {
return Center(child: _indicator(context));
}
return const SizedBox.shrink();
}
}