How to Use setState In Flutter

How to Use setState In Flutter??

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object. So in this article, we will go through How to Use setState In Flutter.

How to Use setState In Flutter??

Anyhow the below snippets are equivalent.

First case

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {

    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

Second case:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    setState(() {});
  }

When you change the state of a Stateful Widget, use setState() to cause a rebuild of the widget and its descendants.
You don’t need to call setState() in the constructor or initState() of the widget, because build() will be run afterwards anyway.

Also don’t call setState() in synchronous code inside build(). You shouldn’t need to cause a rerun of build() from within build().

Generally, it is recommended that the setState method only be used to wrap the actual changes to the state, not any computation that might be associated with the change.

For example, here a value used by the build function is incremented, and then the change is written to disk, but only the increment is wrapped in the setState:

Future<void> _incrementCounter() async {
  setState(() {
    _counter++;
  });
  Directory directory = await getApplicationDocumentsDirectory();
  final String dirName = directory.path;
  await File('$dir/counter.txt').writeAsString('$_counter');
}

Whenever you want to update a widget tree generally with some new data, you call setState. It can only be used in State class. Here’s the simple implementation:

class _MyPageState extends State {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () => setState(() => _count++),
          child: Text('Count = $_count'),
        ),
      ),
    );
  }
}

If you look at the implementation of setState:

void setState(VoidCallback fn) {
   assert(fn != null);
   assert(...);
   final dynamic result = fn() as dynamic;
   assert(...);
   _element.markNeedsBuild();
 }

You see that the only things it does are: asserting a few things to help you debug incorrect usage of it. Executing the callback, and marking the element so it gets rebuilt.

So, technically, it doesn’t matter if you change some variables inside the setState callback or outside. As long as setState is called.

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, we have been through How to Use setState In Flutter.

Keep Learning !!! Keep Fluttering !!! Stay Connected !!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields