一尘不染

如何在Flutter中正确显示Snackbar?

flutter

我试图显示一个Snackbar点击floatingActionbutton。但是,当我单击时,floatingactionbutton它什么也没有显示。这是我的代码。我正在使用StatefulWidget。我调试并检查onPressed函数是否也正在执行,但是以某种方式Snackbar不可见。造成此问题的根本原因是什么?我觉得我传递的BuildContext有问题。

class MyApp extends StatefulWidget{
  @override
  MyAppState createState() {
    // TODO: implement createState
    return new MyAppState();
  }

}

class MyAppState extends State<MyApp>{
  File _image;
  String _text;

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    _image = image;
    final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(_image);
    final TextRecognizer textRecognizer = FirebaseVision.instance.textRecognizer();
    final VisionText visionText = await textRecognizer.processImage(visionImage);

    String detectedText = visionText.text;

    setState(() {
      _image = image;
      _text = detectedText;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: new AppBar(
          title: new Text('Image Picker Example'),
        ),
        body: new Center(
          child: _image == null
              ? new Text('No image selected.')
              : new Image.file(_image),
        ),
        floatingActionButton: new FloatingActionButton(
          onPressed: (){
            showSnackBar(context);
//            getImage();
          },
          tooltip: 'Pick Image',
          child: new Icon(Icons.add_a_photo),
        ),
      ),
    );
  }

  void showSnackBar(BuildContext context) {
    final scaffold = Scaffold.of(context);
    final snackBarContent = SnackBar(
      content: Text("sagar"),
      action: SnackBarAction(
          label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
    );
    scaffold.showSnackBar(snackBarContent);
  }

}

阅读 469

收藏
2020-08-13

共1个答案

一尘不染

发生这种情况是因为BuildContext使用的人没有Scaffold祖先,因此将无法找到它来呈现,SnackBar因为Scaffold要显示它。

根据方法文档:

当实际上在同一构建函数中创建了脚手架时,该构建函数的context参数不能用于找到该脚手架(因为它在返回的小部件“上方”)。在这种情况下,可以使用以下带有Builder的技术来为BuildContext提供“在”脚手架下方的新作用域:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Demo')
    ),
    body: Builder(
      // Create an inner BuildContext so that the onPressed methods
      // can refer to the Scaffold with Scaffold.of().
      builder: (BuildContext context) {
        return Center(
          child: RaisedButton(
            child: Text('SHOW A SNACKBAR'),
            onPressed: () {
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text('Hello!'),
              ));
            },
          ),
        );
      },
    ),
  );
}

与使用@ ,@
Epizon答案已经提到过的相比,将其包装FloatingActionButton在一个Builder小部件中将使它变得更加优雅GlobalKey

2020-08-13