Showing selected image in alert dialog in flutter

泪湿孤枕 提交于 2020-01-06 09:04:10

问题


How can i show the selected image in my alert dialog ?

In my app, i added an alert dialog which has the camera button. When user clicks the camera button, another alert dialog asks to select file from gallery. After the user selects image file from gallery, i want to show the image in the alert dialog with the camera button, but the image shows only after reopening the alert dialog.

I have posted my code below. I am new to flutter. Please can someone help me? Thanks in advance.

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,
          );
        }
      },
    );
  }
}


回答1:


That is because you would need to setState() however you can't do that in an alert dialogue as it doesn't have its own state, the workaround for that would be to have the dialogue be its own stateful widget. Please check out this article as it shows how to do that. If you faced problems let me know!

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));
  }

}


来源:https://stackoverflow.com/questions/56885714/showing-selected-image-in-alert-dialog-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!