In FLUTTER I'm trying to refresh screen 4 times. I've 4 variable 1 Elevated button and if statement. It's changing image for imagePath1, imagePath2, imagePath3 variable but not working for imagePath4 variable.
Here is my variable.
String imagepath1 = 'images/flame-833.png';
String imagepath2 = 'images/flame-859.png';
String imagepath3 = 'images/flame-891.png';
String imagepath4 = 'images/flame-4.png';
String currentPath = imagePath1;
Here is my ElevatedButton with if statement and Image widget.
ElevatedButton(
onPressed: () {
setState(() {
if (currentPath == imagePath1) {
currentPath = imagePath2;
} else if (currentPath == imagepath2) {
currentPath = imagepath3;
} else if (currentPath == imagepath3) {
currentPath = imagepath4;
} else {
currentPath = imagepath1;
}
});
},
child: const Text('Add Image'),
),
Center(child: Image.asset(currentPath)),
- Once I go to this page I get imagePath1 picture.
- Once I click Add image I get imagePath2 picture.
- Once I click Add image 2nd time I get imagePath3 picture.
- Once I click Add image 3rd time I do not get any picture. No screen change.
CodePudding user response:
your code works perfectly, the only problem is that the variables have to be instantiated outside the Widget build
class _TesteScreenState extends State<TesteScreen> {
String imagepath1 = 'images/flame-833.png';
String imagepath2 = 'images/flame-859.png';
String imagepath3 = 'images/flame-891.png';
String imagepath4 = 'images/flame-4.png';
String currentPath = 'images/flame-833.png';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {
setState(() {
if (currentPath == imagepath1) {
currentPath = imagepath2;
} else if (currentPath == imagepath2) {
currentPath = imagepath3;
} else if (currentPath == imagepath3) {
currentPath = imagepath4;
} else {
currentPath = imagepath1;
}
});
},
child: const Text('Add Image'),
),
Center(child: Image.asset(currentPath)),
],
),
);
}
}
CodePudding user response:
Finally I find the solution. Only problem was variable name uppercase and lowercase. But I do not know why flutter did not identify this error.
Here is correct variable names code:
String imagePath1 = 'images/flame-833.png';
String imagePath2 = 'images/flame-859.png';
String imagePath3 = 'images/flame-891.png';
String imagePath4 = 'images/flame-4.png';
String currentPath = imagePath1;
Here is widget code:
ElevatedButton(
onPressed: () {
setState(() {
if (currentPath == imagePath1) {
currentPath = imagePath2;
} else if (currentPath == imagePath2) {
currentPath = imagePath3;
} else if (currentPath == imagePath3) {
currentPath = imagePath4;
} else {
currentPath = imagePath1;
}
});
},
child: const Text('Add Image'),
),
Center(child: Image.asset(currentPath)),