I am trying to show a Snackbar
on click of a floatingActionbutton
. But when I click on the floatingactionbutton
it\'s not showing anyt
That happens because the BuildContext
used has not a Scaffold
ancestor thus, won't be able to find it to render a SnackBar
since it's up to the Scaffold
to display it.
According to the of method documentation:
When the Scaffold is actually created in the same build function, the context argument to the build function can't be used to find the Scaffold (since it's "above" the widget being returned). In such cases, the following technique with a Builder can be used to provide a new scope with a BuildContext that is "under" the Scaffold:
@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!'), )); }, ), ); }, ), ); }
Solution
Wrapping your FloatingActionButton
in a Builder
widget will make it possible in a more elegant way than using a GlobalKey
, which was already mentioned by the @Epizon answer.
class MyApp extends StatefulWidget{
@override
MyAppState createState() {
// TODO: implement createState
return new MyAppState();
}
}
class MyAppState extends State<MyApp>{
final GlobalKey<ScaffoldState> _scaffoldkey = new GlobalKey<ScaffoldState>();
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(
key: _scaffoldkey,
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();
// getImage();
},
tooltip: 'Pick Image',
child: new Icon(Icons.add_a_photo),
),
),
);
}
void showSnackBar() {
final snackBarContent = SnackBar(
content: Text("sagar"),
action: SnackBarAction(
label: 'UNDO', onPressed: _scaffoldkey.currentState.hideCurrentSnackBar),
);
_scaffoldkey.currentState.showSnackBar(snackBarContent);
}
}