Is there a way to use setState with StatelessWidget? I know that I could be used with StatefulWidget and using a State, but I don't know if there's a way to use it with StatelessWidget.
I think that's a direct question and it doesn't need code to be shown.
If you could help me, I will appreciate it.
setState method Null safety Notify the framework that the internal state of this object has changed. Whenever you change the internal state of a State object, make the change in a function that you pass to setState: setState(() { _myState = newValue; }); The provided callback is immediately called synchronously.
A widget is either stateful or stateless. If a widget can change—when a user interacts with it, for example—it's stateful. A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets.
setState is the most common way that we use to rebuild our widget tree to reflect the changes. But, using setState to rebuild the widget tree can be costlier sometimes. Hence there are different state management concepts like provider, BLoC, GetX, etc. that are used to rebuild the UI.
ValueNotifier requires a bit more code than setState . But it can be used to remember the state, by placing a Provider where appropriate in the widget tree.
here is an example of code that makes it possible for a StatelessWidget to update itself, its from an article of Didier Boelens.
https://www.didierboelens.com/2019/09/flutter-internals/ " The following useless code makes possible for a StatelessWidget to update itself (as if it was a StatefulWidget but without using any setState()), by using the BuildContext …
void main(){
runApp(MaterialApp(home: TestPage(),));
}
class TestPage extends StatelessWidget {
// final because a Widget is immutable (remember?)
final bag = {"first": true};
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(title: Text('Stateless ??')),
body: Container(
child: Center(
child: GestureDetector(
child: Container(
width: 50.0,`enter code here`
height: 50.0,
color: bag["first"] ? Colors.red : Colors.blue,
),
onTap: (){
bag["first"] = !bag["first"];
//
// This is the trick
//
(context as Element).markNeedsBuild();
}
),
),
),
);
}
}
Between us, when you are invoking the setState() method, the latter ends up doing the very same thing: _element.markNeedsBuild().
"
No. That's the whole point of StatelessWidget
: It doesn't have a state.
Only StatefulWidget
has a state, and therefore only it has a setState
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With