如何在Flutter中从导航栏调用方法

时间:2019-10-30 13:48:11

标签: flutter flutter-layout flutter-dependencies

我正在尝试从导航栏调用方法,当我调用对象时,已选择图像的对象未出现在屏幕上。

我的目标是这样做,当我单击“图库”并选择新图像时,如屏幕2所示。

First screen to select way to choose the image

The screen that I want to show when I selected the photo

此交互的代码

  File imageFile;

  _openGallery(BuildContext context) async{
    var picture = await ImagePicker.pickImage(source:ImageSource.gallery);
    this.setState((){
      imageFile = picture;
    });
    Navigator.of(context).pop();
  }


  _openCamera(BuildContext context) async{
    var picture = await ImagePicker.pickImage(source:ImageSource.camera);
    this.setState((){
      imageFile = picture;
    });
    Navigator.of(context).pop();
  }

还有构建小部件

@override
  Widget build(BuildContext context) {
    return Scaffold(


        body: Container(
          child: Center(
              child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                _decideImageView(),
                RaisedButton(onPressed: (){
                  _showChoiceDialog(context);
                },child: Text('Select Image'),),
                _decideButton(context)

              ],
            ),
          ),
        ),

        bottomNavigationBar: BottomNavigationBar(
        type:BottomNavigationBarType.fixed,
        onTap: (int index) {
          if (index==0)
            _openGallery(context);
          if (index == 1)
            _openCamera(context);
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.photo_library),
            title: Text('Home')
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.camera_alt),
            title: Text('Camera')
          ),
         ],
      ),

    );
  }

以下是确定是否要在屏幕上询问文本以选择图像或返回图像的函数,该方法称为_decideImageView。

  Widget _decideImageView(){
    if(imageFile == null){
      return Text('Kein Bild ausgewählt',
       style: TextStyle(
                                    color:Colors.black,
                                    fontFamily: 'Lato', 
                                    fontSize: 25,
                                    letterSpacing: 1.0
                                    ),          );
    }
    else{

      return Image.file(imageFile,width:400,height:400);
    }
  }

1 个答案:

答案 0 :(得分:1)

尝试删除此内容:Navigator.of(context).pop();  关于两种选择图片的方法,这对我来说很奏效,但是您需要知道,这不是创建图像选择器的最佳方法。