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

How to call a method from navbar in Flutter

我试图从导航栏调用一个方法,当我调用该对象时,图像 selected 没有出现在屏幕上。

我的目标是这样做,当我在图库中单击并 select 新图像时,像屏幕 2 中那样显示。

此交互的代码,

  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')
          ),
         ],
      ),

    );
  }

决定您是否会看到要求 select 图片或 return 屏幕上的图片的函数是下面这个,该方法称为 _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);
    }
  }

尝试删除这个:Navigator.of(context).pop(); 关于选择图片的两种方法,这对我有用,但你需要知道这不是创建图像选择器的最佳方法。