在抖动对话框中显示选定的图像

时间:2019-07-04 10:14:24

标签: flutter flutter-layout

如何在警报对话框中显示所选图像?

在我的应用程序中,我添加了一个带有照相机按钮的警报对话框。当用户单击相机按钮时,另一个警报对话框会要求从图库中选择文件。用户从图库中选择图像文件后,我想使用相机按钮在警报对话框中显示图像,但是该图像仅在重新打开警报对话框后才显示。

我在下面发布了我的代码。我是新来的扑扑。有人可以帮我吗?预先感谢。

class Test extends StatefulWidget {
  @override
  _State createState() => new _State();
}
Future<File> imageFile;
class _State extends State<Test> {
  Future<void> _openDailog() async {

    return showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          shape:
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text('Click Photo'),
              Ink(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(24.0),
                    color: Colors.blue),
                child: IconButton(
                  color: Colors.white,
                  icon: Icon(Icons.camera_alt),
                  onPressed: () {
                    _cameraOptions();
                   print("test");
                  },
                ),
              )
            ],
          ),
          content: SingleChildScrollView(
            child: Container(
              width: 300.0,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  showImage(),
                  InkWell(
                      child: Container(
                        margin: EdgeInsets.only(top: 8.0),
                        child: RaisedButton(
                          color: Colors.blue,
                          child: new Text(
                            "Send",
                            style: TextStyle(color: Colors.white),
                          ),
                          onPressed: () {
                            Navigator.of(context).pop();
                            print("test");
                          },
                        ),
                      )),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return  Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        FloatingActionButton(
        heroTag: null,
        child: Icon(Icons.insert_drive_file),
        onPressed: () {
          _openDailog();
        },
        )
      ],
    );
  }
  Future<void> _cameraOptions() {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: new SingleChildScrollView(
              child: new ListBody(
                children: <Widget>[
                  FlatButton(
                    onPressed: () {
                      pickImageFromGallery(ImageSource.gallery);
                      Navigator.of(context).pop();
                    },
                    color: Colors.transparent,
                    child: new Text(
                      'Select From Gallery',
                      textAlign: TextAlign.start,
                      style: new TextStyle(
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }
  pickImageFromGallery(ImageSource source) {
    setState(() {
      imageFile = ImagePicker.pickImage(source: source);
    });
  }
  Widget showImage() {
    return FutureBuilder<File>(
      future: imageFile,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            snapshot.data != null) {
          return Image.file(
            snapshot.data,
            width: MediaQuery.of(context).size.width,
            height: 100,
          );
        } else if (snapshot.error != null) {
          return const Text(
            'Error Picking Image',
            textAlign: TextAlign.center,
          );
        } else {
          return const Text(
            'No Image Selected',
            textAlign: TextAlign.center,
          );
        }
      },
    );
  }
}

3 个答案:

答案 0 :(得分:0)

那是因为您需要setState(),但是您不能在警报对话框中执行此操作,因为它没有自己的状态,因此解决方法是将对话框设为自己的有状态小部件。请查看this article,因为它显示了如何执行此操作。如果您遇到问题,请告诉我!

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

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}


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

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;


  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("StackoverFlow"),
      ),
      body: Container(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await _dialogCall(context);
        },
      ),
    );
  }

  Future<void> _dialogCall(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return MyDialog();
        });
  }
}


class MyDialog extends StatefulWidget {
  @override
  _MyDialogState createState() => new _MyDialogState();
}

class _MyDialogState extends State<MyDialog> {

  String imagePath;
  Image image;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: new SingleChildScrollView(
        child: new ListBody(
          children: <Widget>[
            Container(child: image!= null? image:null),
            GestureDetector(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.camera),
                    SizedBox(width: 5),
                    Text('Take a picture                       '),
                  ],
                ),
                onTap: () async {
                  await getImageFromCamera();
                  setState(() {

                  });
                }),
            Padding(
              padding: EdgeInsets.all(8.0),
            ),
          ],
        ),
      ),
    );
  }


  Future getImageFromCamera() async {
    var x = await ImagePicker.pickImage(source: ImageSource.camera);
    imagePath = x.path;
    image = Image(image: FileImage(x));
  }

}

答案 1 :(得分:0)

我尝试了此操作,但是容器未显示图像。ScreenShot

import 'dart:convert';

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

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}


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

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;


  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("StackoverFlow"),
      ),
      body: Container(),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          await _dialogCall(context);
        },
      ),
    );
  }

  Future<void> _dialogCall(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return MyDialog();
        });
  }
}


class MyDialog extends StatefulWidget {
  @override
  _MyDialogState createState() => new _MyDialogState();
}

class _MyDialogState extends State<MyDialog> {

  String imagePath;
  Image image;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: new SingleChildScrollView(
        child: new ListBody(
          children: <Widget>[
            Container(child: image!= null? image:null),
            GestureDetector(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.camera),
                    SizedBox(width: 5),
                    Text('Take a picture                       '),
                  ],
                ),
                onTap: () async {
                  await getImageFromCamera();
                  setState(() {

                  });
                }),
            Padding(
              padding: EdgeInsets.all(8.0),
            ),
          ],
        ),
      ),
    );
  }


  Future getImageFromCamera() async {
    var x = await ImagePicker.pickImage(source: ImageSource.camera);
//    imagePath = x.path;
    image = Image(image: FileImage(x));
  }

}

答案 2 :(得分:0)

尝试使用GestureDetector()解决方案。

onTap:()async{
var image = await ImagePicker.pickImage(
source: ImageSource.gallery).whenComplete((){
      setState(() { 
      });
  }
  );
 setState(() {
  _image = image;
  });

 },