Using setState with StatelessWidget

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.


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().

Tags:

Dart

Flutter