I need some help, I tried to make a code in flutter that moves the background image with AnimatedPositioned, but I found the following error:
The method ‘setState’ isn’t defined for the type ‘TerceiraRota’. (Documentation) Try correcting the name to the name of an existing method, or defining a method named ‘setState’.
Can someone help me?
Tks!
class TerceiraRota extends StatelessWidget {
double position=0;
bool isFlipped=false;
bool isStart=false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sad Shrek Adventures"),
),
body: Stack(
children: [
AnimatedPositioned(
top: -100,
left: position,
height: 660,
child: Image.asset('imagens/swamp.jpg'),
duration: Duration(microseconds: 200)),
Positioned(
top:470,
left: 180,
child: Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(
image:DecorationImage(
image:AssetImage(
"imagens/shrektriste2.png"
),
)
),
),
),
Positioned(
top:400,
left:MediaQuery.of(context).size.width/2-85,
child: IconButton(
icon:Icon(Icons.arrow_back_ios),
onPressed: () {
setState(() {
position -= 40;
});
})
),],
),
);
}
} ```
3
Answers
You need to use a
StatefulWidget
, in your code above you have extendedStatelessWidget
. Since the theStatelessWidget
can not hold or modify the state of the widget it does not have the functionsetState
, hence the name Stateless.Have a look at the documentation, you can find good examples there.
You create a StatelessWidget.
StatelessWidget don’t have state, so… setstate don’t work.
If you want work with state, change your widget to a statefull widget.
Android Studio and VsCode make this change easy.
Put your mouse in Stateless word, click in the yellow lamp and choose "Convert to statefull widget".
You need to use the
StatefulWidget
instead ofStatelessWidget
like this: