線上書籍

Home

Dart 及 flutter 初體驗

import 'package:flutter/material.dart'; import 'dart:io'; 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: '拍照', theme: ThemeData( primarySwatch: Colors.blue, ), home: PhotoPage(title: '拍照App'), ); } } class PhotoPage extends StatefulWidget { PhotoPage({Key key, this.title}) : super(key: key); final String title; @override _PhotoPageState createState() => _PhotoPageState(); } class _PhotoPageState extends State<PhotoPage> { File _image; final picker = ImagePicker(); Future getImage(bool isTakePhoto) async { //去除底部彈框 Navigator.pop(context); final pickedFile = await picker.getImage(source: isTakePhoto?ImageSource.camera:ImageSource.gallery); setState(() { if (pickedFile != null) { _image = File(pickedFile.path); } else { print('No image selected.'); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( '相片列表', style: Theme.of(context).textTheme.headline4, ), _image == null ? Text('No image selected.') : Image.file(_image), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _pickImage, tooltip: '選擇圖片', child: Icon(Icons.add_a_photo), ), // This trailing comma makes auto-formatting nicer for build methods. ); } void _pickImage() { //底部彈框 showModalBottomSheet(context: context, builder: (context)=>Container( height: 140.0, child: Column( children: [ _item('相機拍照', true), _item('從相簿選擇', false) ], ), )); } _item(String title, bool isTakePhoto) { return GestureDetector( child: ListTile( leading: Icon(isTakePhoto?Icons.camera_alt:Icons.photo_album), title:Text(title), onTap: ()=>getImage(isTakePhoto), ), ); } }