forked from flutter/packages
/
open_image_page.dart
97 lines (87 loc) · 2.91 KB
/
open_image_page.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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// Screen that allows the user to select an image file using
/// `openFiles`, then displays the selected images in a gallery dialog.
class OpenImagePage extends StatelessWidget {
/// Default Constructor
const OpenImagePage({Key? key}) : super(key: key);
Future<void> _openImageFile(BuildContext context) async {
const XTypeGroup typeGroup = XTypeGroup(
label: 'images',
extensions: <String>['jpg', 'png'],
macUTIs: <String>['public.image'],
);
final XFile? file = await FileSelectorPlatform.instance
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
if (file == null) {
// Operation was canceled by the user.
return;
}
final String fileName = file.name;
final String filePath = file.path;
if (context.mounted) {
await showDialog<void>(
context: context,
builder: (BuildContext context) => ImageDisplay(fileName, filePath),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open an image'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
// TODO(darrenaustin): Migrate to new API once it lands in stable: https://github.com/flutter/flutter/issues/105724
// ignore: deprecated_member_use
primary: Colors.blue,
// ignore: deprecated_member_use
onPrimary: Colors.white,
),
child: const Text('Press to open an image file(png, jpg)'),
onPressed: () => _openImageFile(context),
),
],
),
),
);
}
}
/// Widget that displays an image in a dialog.
class ImageDisplay extends StatelessWidget {
/// Default Constructor.
const ImageDisplay(this.fileName, this.filePath, {Key? key})
: super(key: key);
/// The name of the selected file.
final String fileName;
/// The path to the selected file.
final String filePath;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(fileName),
// On web the filePath is a blob url
// while on other platforms it is a system path.
content: kIsWeb ? Image.network(filePath) : Image.file(File(filePath)),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
}
}