Preview photo after camera takes picture - flutter

When a user takes a photo, I want to send it to the photo_preview screen, which gives the user the chance to take another photo.
This page is as follows:
import 'package:flutter/material.dart';
import 'dart:io';
class photo_previewScreen extends StatelessWidget {
final String imagePath;
const photo_previewScreen({Key key, this.imagePath}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
body: Image.file(File(imagePath)),
);
}
}
On my current camera page, what's the best way for me to send the photo to the above page?
When the take picture button is pressed, this is what is currently happening:
onPressed: () {
_openGallery();
Navigator.pop(context);
},
EDIT: Full page with edits from the answer
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'dart:io';
import 'package:stumble/pages/PhotoPreviewScreen.dart';
class Camera extends StatefulWidget {
Function setData;
Camera({Key key, this.setData}) : super(key: key);
#override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<Camera> {
CameraController controller;
List cameras;
int selectedCameraIndex;
String imgPath;
var image;
takePicture;
Future _openGallery() async {
image = await controller.takePicture();
if (widget.setData != null) {
widget.setData(File(image.path));
}
}
#override
void initState() {
super.initState();
availableCameras().then((availableCameras) {
cameras = availableCameras;
if (cameras.length > 0) {
setState(() {
selectedCameraIndex = 0;
});
_initCameraController(cameras[selectedCameraIndex]).then((void v) {});
} else {
print('No camera available');
}
}).catchError((err) {
print('Error :${err.code}Error message : ${err.message}');
});
}
Future _initCameraController(CameraDescription cameraDescription) async {
if (controller != null) {
await controller.dispose();
}
controller = CameraController(cameraDescription, ResolutionPreset.high);
controller.addListener(() {
if (mounted) {
setState(() {});
}
if (controller.value.hasError) {
print('Camera error ${controller.value.errorDescription}');
}
});
try {
await controller.initialize();
} on CameraException catch (e) {}
if (mounted) {
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 1,
child: _cameraPreviewWidget(),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 120,
width: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[_cameraControlWidget(context), Spacer()],
),
),
)
],
),
),
),
);
}
Widget _cameraPreviewWidget() {
if (controller == null || !controller.value.isInitialized) {
return const Text(
'Loading',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w900,
),
);
}
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
return Stack(children: <Widget>[
Positioned.fill(
child: new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: new CameraPreview(controller),
),
),
]);
}
Widget _cameraControlWidget(context) {
return Expanded(
child: Align(
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
FloatingActionButton(
child: Icon(
Icons.center_focus_strong,
size: 39,
color: Color(0xffffffff),
),
backgroundColor: Color(0xff33333D),
onPressed: () async {
var result = await takePicture();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoPreviewScreen(
imagePath: result,
),
),
);
})
],
),
),
);
}
}
I am getting the error that
'The method 'takePicture isn't defined for the type '_CameraScreenState'
This despite takePicture(); being defined.

You can navigate to the preview screen on clicking the take picture button, passing the image path:
void onTakePictureButtonPressed() async {
var result = await takePicture();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoPreviewScreen(
imagePath: result,
),
),
);
}
Future<String> takePicture() async {
if (!controller.value.isInitialized) {
showErrorFlushbar(context, 'Error: select a camera first.');
return null;
}
final Directory extDir = await getApplicationDocumentsDirectory();
final String dirPath = '${extDir.path}/Pictures/ompariwar';
await Directory(dirPath).create(recursive: true);
final String filePath = '$dirPath/${timestamp()}.jpg';
if (controller.value.isTakingPicture) {
// A capture is already pending, do nothing.
return null;
}
try {
await controller.takePicture(filePath);
} on CameraException catch (e) {
print(e);
return null;
}
return filePath;
}
In the preview screen, you can do this:
class PhotoPreviewScreen extends StatelessWidget {
final String imagePath;
const PhotoPreviewScreen({Key key, this.imagePath}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pop(context), // Go back to the camera to take the picture again
child: Icon(Icons.camera_alt),
),
appBar: AppBar(title: Text('Display the Picture')),
body: Column(
children: [
Expanded(child: Image.file(File(imagePath))),
SomeButton(), // Add a button to send the image to server or go back to home screen here
],
),
);
}
}
Btw it's a convention to name your class/ Widget name in UpperCamelCase. Read more on this Dart style guide for clean code.

Related

How to retrieve the data shown on the chat screen using streambuilder

I was trying to get the data from firebase to my chat screen using snapshot data but I am unable to get that as the message.data['text'] and sender gives me error. I want to display the name and the message all on the screen for now so please suggest the fix for this code or a alternative way for that
message code
import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
static String id = 'chat_screen';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
User loggedInUser;
String message;
#override
void initState() {
// TODO: implement initState
getCurrentUser();
super.initState();
}
void getCurrentUser() {
try {
final user = _auth.currentUser;
if (user != null) {
loggedInUser = user;
// print(loggedInUser.email);
}
} catch (e) {
print(e);
}
}
void messageStream() async {
await for (var snapshot in _firestore.collection('messages').snapshots()) {
for (var message in snapshot.docs) {
print(message.data());
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
messageStream();
//Implement logout functionality
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
}
final messages = snapshot.data.docs;
List<Text> messagesWidgets = [];
for (var message in messages) {
final messageText = message.data['text']; //error
final messageSender = message.data['sender']; //error
final messageWidget = Text('$messageText from
$messageSender');
messageWidgets.add(messageWidget)
}
return Column(
children: messagesWidgets,
);
},
),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) {
message = value;
//Do something with the user input.
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
//message + loggedInuser.email
//Implement send functionality
_firestore.collection('messages').add({
'text': message,
'sender': loggedInUser.email,
});
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}

Flutter not rendering page correctly when page is called after camera is used

I've been building an app in flutter for the past while and recently I added camera functionality. I've a button on my home page that directs me to a camera page with the camera preview, on the camera preview page I have a home icon which directs back to the home page.
I've noticed when I click the home page from the camera page it doesn't render correctly, I've multiple calls to the home page throughout the project and they all work fine its only when accessing from the camera page. I added then((value) => setState(() {})); to try and reset the state of the home page and I can see its being called but with no luck regarding the rendering[![enter image description here][1]][1]
I've added a picture of the Home Screen render issue, its worth noting im getting no errors on Xcode.
Camera screen code:
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:moodful/Screens/HomeScreen/home_screen.dart';
import 'package:moodful/Screens/Login/login_screen.dart';
import 'package:moodful/main.dart';
import '../constants.dart';
class CameraPage extends StatefulWidget {
final List<CameraDescription>? cameras;
const CameraPage({this.cameras, Key? key}) : super(key: key);
#override
_CameraPageState createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage> {
late CameraController controller;
// used to increment camera switch tap
int cameraIconTap = 0;
XFile? pictureFile;
#override
void initState() {
super.initState();
controller = CameraController(
widget.cameras![0],
ResolutionPreset.veryHigh,
);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
if (!controller.value.isInitialized) {
return const SizedBox(
child: Center(
child: CircularProgressIndicator(),
),
);
}
return Scaffold(
appBar: AppBar(
backgroundColor: kPrimaryColor,
centerTitle: true,
title: Text('AppBar'),
leading: IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => HomeScreen()),
).then((value) => setState(() {}));
print("refresh done ");
},
icon: Icon(Icons.home),
),
actions: [
IconButton(
onPressed: () {
//increment on tap, calculate modulus, pass to widget.camera. 0 == rear camera, 1 == front camera
cameraIconTap++;
int modulusTap;
modulusTap = cameraIconTap % 2;
if (widget.cameras!.length > 1) {
setState(() {
controller = CameraController(
widget.cameras![modulusTap], ResolutionPreset.veryHigh);
});
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('No secondary camera found'),
duration: Duration(seconds: 2),
));
}
},
icon: const Icon(Icons.cameraswitch),
),
],
),
body: Center(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(8.0, 20.0, 8.0, 8.0),
child: Column(
children: [
Center(
child: SizedBox(
height: //400
size.height / controller.value.aspectRatio,
width: size.width * 1.3 / controller.value.aspectRatio,
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
),
),
),
],
),
),
//),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () async {
pictureFile = await controller.takePicture();
setState(() {});
},
child: const Text('Capture Image'),
),
),
if (pictureFile != null)
Image.network(
pictureFile!.path,
height: 200,
)
//Android/iOS
// Image.file(File(pictureFile!.path)))
],
)));
}
}
Home Screen code:
import 'package:camera/camera.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:moodful/components/background.dart';
import 'package:moodful/Screens/Login/login_screen.dart';
import 'package:moodful/components/camera_screen.dart';
import 'package:moodful/main.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Future<DocumentSnapshot<Map<String, dynamic>>>? _fetchedData;
#override
void initState() {
super.initState();
_fetchedData = getData();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return FutureBuilder(
future: _fetchedData,
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.hasData) {
return BackgroundLogoRight(
text: "Home",
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Spacer(),
Expanded(
flex: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 10,
child: Text(
"${snapshot.data!.data()!["firstName"]} \n\n "
"Glad you're back, please enter a mood for today.\n\n "
"Be sure to check the insights page for the most up to date mood analysis\n\n"
"The more you know the more control you have",
style: TextStyle(color: Colors.black, fontSize: 15),
textAlign: TextAlign.center,
),
),
],
),
),
Expanded(
flex: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () async {
await availableCameras().then(
(value) => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CameraPage(
cameras: value,
),
),
),
);
}, // handle your image tap here
child: Image.asset(
"assets/images/recordMoodLogo.jpg",
width: size.width * 0.5,
fit: BoxFit.cover, // this is the solution for border
height: 110.0,
),
),
],
),
),
],
),
);
} else {
return CircularProgressIndicator();
}
},
);
}
Future<DocumentSnapshot<Map<String, dynamic>>> getData() async {
var currentUser = FirebaseAuth.instance.currentUser;
return await FirebaseFirestore.instance
.collection('USER_TABLE')
.doc(currentUser!.uid)
.get();
}
}
Thanks!
[1]: https://i.stack.imgur.com/pbC0w.png

How to hide or show widget built inside FutureBuilder based on daynamic changes

Am able to show and hide the widget i want but it keeps flickering or rebuilding its self every time.
i just want to show the the capture icon button when the compass degree reaches 190 degree
this is my main widget
late List<CameraDescription> cameras;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: CameraApp(),
);
}
}
class CameraApp extends StatefulWidget {
#override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
String? imagePath;
XFile? imageFile;
late CameraController controller;
late Future<void> _initializeControllerFuture;
int? angleResult;
bool showCaptureButton = false;
String? getLocation;
bool k = false;
void getAngleFromCompass(newResult) {
WidgetsBinding.instance!.addPostFrameCallback((_) {
setState(() {
angleResult = newResult;
});
});
}
void getLocationRes(newResult) {
getLocation = newResult;
}
#override
void initState() {
super.initState();
controller = CameraController(
// Get a specific camera from the list of available cameras.
cameras[0],
// Define the resolution to use.
ResolutionPreset.high,
imageFormatGroup: ImageFormatGroup.yuv420,
);
_initializeControllerFuture = controller.initialize().then((value) {
setState(() {});
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
void _captureImage() async {
await takePicture().then((filePath) {
if (mounted) {
setState(() {
imagePath = filePath;
});
}
});
}
Widget cameraWidget(context) {
var camera = controller.value;
final size = MediaQuery.of(context).size;
var scale = size.aspectRatio * camera.aspectRatio;
if (scale < 1) scale = 1 / scale;
return Transform.scale(
scale: scale,
child: Center(
child: CameraPreview(controller),
),
);
}
#override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
theCompassApp(getAngleFromCompass) keeps flikering here
return Scaffold(
body: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Stack(
children: [
cameraWidget(context),
Align(
alignment: Alignment.topCenter,
child: LocationApp(getLocationRes),
),
Align(
child: CompassApp(getAngleFromCompass),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
color: Color(0xAA333639),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
angleResult == 190 ? IconButton(
onPressed: () => _captureImage(),
iconSize: 40,
icon: Icon(
Icons.camera_alt,
color: Colors.white,
),
) : Text(''),
],
),
),
)
],
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Compass App Widget
class CompassApp extends StatefulWidget {
final getAngleValue;
CompassApp(this.getAngleValue);
#override
_CompassAppState createState() => _CompassAppState();
}
class _CompassAppState extends State<CompassApp> {
bool _hasPermissions = false;
#override
void initState() {
super.initState();
_fetchPermissionStatus();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.transparent,
body: Builder(builder: (context) {
if (_hasPermissions) {
return Column(
children: <Widget>[
Expanded(child: _buildCompass()),
],
);
} else {
return Text('');
}
}),
),
);
}
Widget _buildCompass() {
return StreamBuilder<CompassEvent>(
stream: FlutterCompass.events,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 30),
child: Text('Error reading heading not support'),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
double? direction = snapshot.data!.heading;
int ang = direction!.round();
Compass angle passed to main widget here
widget.getAngleValue(ang);
if (direction.isNaN)
return Center(
child: Text("Device does not have sensors !"),
);
return Material(
color: Colors.transparent,
child: Column(
children: [
RotatedBox(
quarterTurns: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 41),
child: Text(
'$ang',
style: TextStyle(
fontSize: 50,
color: Colors.white,
backgroundColor: Colors.black26),
),
),
),
],
),
);
},
);
}
void _fetchPermissionStatus() {
Permission.locationWhenInUse.status.then((status) {
if (mounted) {
setState(() => _hasPermissions = status == PermissionStatus.granted);
}
});
}
}
Have you tried Visibility or Opacity?
Visibility
Visibility(
visible: true, //false for invisible
child: Text('I am visible'),
),
Opacity
Opacity(
opacity: 1.0, //0.0 for invisible
child: Text('I am visible'),
),

Camera preview stretched vertically

My camera preview is currently stretched vertically as per the screenshot attached.
The code to the camera page is below, does anyone know how to adjust the code so that the camera preview does not appear to be stretched?
I need it to work for iOS and Android, and for every device.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'dart:io';
import 'package:flutter/services.dart';
class Camera extends StatefulWidget {
Function setData;
Camera({Key key, this.setData}) : super(key: key);
#override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<Camera> {
CameraController controller;
List cameras;
int selectedCameraIndex;
String imgPath;
var image;
Future _openGallery() async {
image = await controller.takePicture();
if (widget.setData != null) {
widget.setData(File(image.path));
}
}
#override
void initState() {
super.initState();
SystemChrome.setEnabledSystemUIOverlays([]);
availableCameras().then((availableCameras) {
cameras = availableCameras;
if (cameras.length > 0) {
setState(() {
selectedCameraIndex = 0;
});
_initCameraController(cameras[selectedCameraIndex]).then((void v) {});
} else {
print('No camera available');
}
}).catchError((err) {
print('Error :${err.code}Error message : ${err.message}');
});
}
Future _initCameraController(CameraDescription cameraDescription) async {
if (controller != null) {
await controller.dispose();
}
controller = CameraController(cameraDescription, ResolutionPreset.high);
controller.addListener(() {
if (mounted) {
setState(() {});
}
if (controller.value.hasError) {
print('Camera error ${controller.value.errorDescription}');
}
});
try {
await controller.initialize();
} on CameraException catch (e) {}
if (mounted) {
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Stack(
children: <Widget>[
_cameraPreviewWidget(),
_cameraControlWidget(context)
],
),
),
);
}
Widget _cameraPreviewWidget() {
if (controller == null || !controller.value.isInitialized) {
return const Text(
'Loading',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w900,
),
);
}
final size = MediaQuery.of(context).size;
final deviceRatio = size.width / size.height;
return Stack(children: <Widget>[
Positioned.fill(
child: new AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: new CameraPreview(controller),
),
),
]);
}
Widget _cameraControlWidget(context) {
return Container(
child: Align(
alignment: Alignment.center,
child: FloatingActionButton(
child: Icon(
Icons.center_focus_strong,
size: 39,
color: Color(0xd),
),
backgroundColor: Color(0xff33333D),
onPressed: () {
_openGallery();
Navigator.pop(context);
},
)
));
}
}
and here is the image as to how it is rendering. The button in the middle takes the photo.
I have struggled with the camera preview in Flutter as well. It is a pain to work with. This is what I am using right now. Hopefully it will help you
class CameraPreview extends StatelessWidget {
const CameraPreview({Key? key, this._cameraController}) : super(key: key);
final CameraController _cameraController;
#override
Widget build(BuildContext context) {
return ClipRect(
child: OverflowBox(
alignment: Alignment.center,
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
height: 1,
child: AspectRatio(
aspectRatio: 1 / _cameraController.value.aspectRatio,
child: CameraPreview(_cameraCcontroller),
),
),
),
),
);
}
}

how to know the height and width of the image which we fetch from gallery

I know how to fetch a image from the gallery but stuck in a part where i want to know how to fetch the information of the image which i am fetching for example i want to know the height and width of the image i am fetching.
If someone getting what i am trying to say please help thanks in advance.
I have written a code just to fetch image and its below.
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
void main() {
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
File imageFile;
_openCamera(BuildContext context) async {
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
this.setState(() {
imageFile = picture;
});
Navigator.of(context).pop();
}
_openGallery(BuildContext context) async {
var picture = await ImagePicker.pickImage(
source: ImageSource.gallery, maxHeight: 400, maxWidth: 400);
this.setState(() {
imageFile = picture;
});
Navigator.of(context).pop();
}
Future<void> _showChoiceDialog(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Choose one"),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
GestureDetector(
child: Text("gallery"),
onTap: () {
_openGallery(context);
},
),
Padding(padding: EdgeInsets.all(10.0)),
GestureDetector(
child: Text("Camera"),
onTap: () {
_openCamera(context);
},
),
],
)),
);
});
}
Widget _DecideImageView() {
if (imageFile == null) {
return Text("Nothing to show");
} else {
return Image.file(
imageFile,
width: 400,
height: 400,
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fetching Image"),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
_DecideImageView(),
Text(
"No Image Selected ",
style: TextStyle(fontWeight: FontWeight.bold),
),
RaisedButton(
onPressed: () {
_showChoiceDialog(context);
},
child: Text("Select Image"))
],
))));
}
}