I have an alert dialog that contains a Camera Preview from the camera package, and after I take a picture, I want the alert dialog to instead show a loading screen. I was hoping to accomplish this by using a ternary operator in the dialog. Below is the dialog I call when I press a button, where isCalculating is a bool that is originally set to false, _initializeControllerFuture initializes the camera, Loading() is the loading screen, and Stack() has the Camera Preview as well as some other things.
cameraDialog(context) async {
await showDialog(
barrierDismissible: false,
context: context,
builder: (_) => AlertDialog(
insetPadding: EdgeInsets.all(5.0),
contentPadding: EdgeInsets.all(3.0),
content: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return isCalculating
? Loading()
: Stack(
In the cameraDialog I have a button that takes a picture, sets the bool isCalculating to true, runs some other code, and sets the bool isCalculating back to false. During this time I want the alert dialog to update its UI and show the Loading() widget. Below is the on pressed event for the button in the cameraDialog:
onPressed: () async {
originalFile = await controller.takePicture();
setState(() {
isCalculating = true;
});
... other code is run here ...
Navigator.of(context).pop();
setState(() {
isCalculating = false;
});
},
CodePudding user response:
As you can see cameraDialog
is a function which is triggered by also a function like onPress
or onTap
. When you call setState
its really call Widget build(BuildContext context)
method and rebuilt the widget tree but it never handle the state of a function or inside a function's content. So calling setState
where you use it has no usefulness. So what you can do? you can create a StatefullWidget
ex- MyAlertDialog
and show it like
onTap: ()=> showDialog(context: context, builder: (ctx) => MyAlertDialog()),
and inside MyAlertDialog
you can handle your state just like you did here.