在 Flutter 中,我们可以利用 image_picker 插件从图库中添加图片。为了实现这一功能,你需要使用真机进行测试。
实现图库和相机访问的步骤
第 1 步:创建一个新的 Flutter 应用
在命令行(Command Prompt)中创建一个新的 Flutter 应用。要创建一个新应用,请输入以下命令并运行。
flutter create app_name
> 想要了解更多,请参考这篇文章:在 Flutter 中创建一个简单的应用
第 2 步:添加依赖项
要将依赖项添加到 pubspec.yaml 文件 中,请在 pubspec.yaml 文件 的 dependencies 部分添加 image_picker 作为依赖项,如下所示:
Dart
CODEBLOCK_4bcd0709
现在在终端中运行以下命令。
CODEBLOCK_086db09b
### 第 3 步:导入依赖项
在 ****main.dart 文件**** 中使用以下代码行来导入 ****image_picker **** 依赖项:
CODEBLOCK_8d04f477
### ****第 4 步:**** 完成最终的应用程序代码
****- 创建一个按钮****
用于显示选择器的类型(图库或相机)。
Dart
CODEBLOCKd6316c93INLINECODE9ff917be
– 显示选择器
显示图库和相机这两个选择器选项,并根据下面提到的选择器类型调用相应的 getImage()。
- gallery : getImage(ImageSource.gallery)
- camera : getImage(ImageSource.camera)
Dart
CODEBLOCK_eb5068ad
### ****完整源代码****
****main.dart: ****
Dart
“`
import ‘dart:io‘;
import ‘package:flutter/material.dart‘;
import ‘package:imagepicker/imagepicker.dart‘;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primaryColor: Colors.green),
home: const GalleryAccess(),
debugShowCheckedModeBanner: false,
);
}
}
class GalleryAccess extends StatefulWidget {
const GalleryAccess({super.key});
@override
State createState() => _GalleryAccessState();
}
class _GalleryAccessState extends State {
File? galleryFile;
final picker = ImagePicker();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(‘Gallery Access and Camera‘),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
actions: const [
Text(
"GFG",
textScaleFactor: 3,
style: TextStyle(color: Colors.white),
),
],
),
body: Builder(
builder: (BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white),
child: const Text(‘Select Image from Gallery and Camera‘),
onPressed: () {
_showPicker(context: context);
},
),
const SizedBox(
height: 20,
),
SizedBox(
height: 200.0,
width: 300.0,
child: galleryFile == null
? const Center(child: Text(‘Sorry nothing selected!!‘))
: Center(child: Image.file(galleryFile!)),
),
],
),
);
},
),
);
}
void _showPicker