天天看點

Flutter實作拍照和相冊選取圖檔功能

1.添加依賴

在pubspec.yaml加入image_picker的依賴:

2.在main.dart導入需要使用的包

3.先實作一個FloatingActionButton

先實作一個FloatingActionButton用于觸發圖檔選擇,完整代碼如下:

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        child: _image == null
            ? Text('No image selected.')
            : Image.file(_image),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed:(){
        },
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}
           

效果如下:

Flutter實作拍照和相冊選取圖檔功能

4.實作FloatingActionButton的點選事件

在點選FloatingActionButton時彈出一個模仿ios效果的選擇框,用于選擇是拍照還是相冊選擇圖檔,代碼如下:

onPressed:(){
          showDemoActionSheet(
            context: context,
            child: CupertinoActionSheet(
              title: const Text('Select photos'),
              //message: const Text('Please select the best mode from the options below.'),
              actions: <Widget>[
                CupertinoActionSheetAction(
                  child: const Text('Gallery'),
                  onPressed: () {
                    Navigator.pop(context, 'Gallery');
                  },
                ),
                CupertinoActionSheetAction(
                  child: const Text('Camera'),
                  onPressed: () {
                    Navigator.pop(context, 'Camera');
                  },
                ),
              ],
              cancelButton: CupertinoActionSheetAction(
                child: const Text('Cancel'),
                isDefaultAction: true,
                onPressed: () {
                  Navigator.pop(context, 'Cancel');
                },
              ),
            ),
          );
        },
           

showDemoActionSheet方法的實作如下:

void showDemoActionSheet({BuildContext context, Widget child}) {
    showCupertinoModalPopup<String>(
      context: context,
      builder: (BuildContext context) => child,
    ).then((String value) {
      if (value != null) {
          if(value == "Camera"){
            getImageByCamera();
          }else if(value == "Gallery"){
            getImageByGallery();
          }
      }
    });
  }
           

效果如下所示:

Flutter實作拍照和相冊選取圖檔功能

5.實作跳轉相機拍照和相冊選擇圖檔方法

getImageByCamera()方法具體代碼如下:

Future getImageByCamera() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _image = image;
    });
  }
           

getImageByGallery()方法具體代碼如下:

Future getImageByGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      _image = image;
    });
  }
           

以上,就是全部代碼了!