setState() or markNeedsBuild called during build

Cover Image for setState() or markNeedsBuild called during build
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Blog Post: Understanding and Fixing "setState() or markNeedsBuild called during build" Error

šŸ‘‹ Hey there, tech enthusiasts! Today, we're going to tackle a common issue that many Flutter developers face: the dreaded "setState() or markNeedsBuild called during build" error. šŸ¤Æ This error usually occurs when you try to update the state of a widget while it's still being built. But don't worry ā€“ we've got your back! Let's dive in and find some easy solutions to resolve this error. šŸ’Ŗ

Understanding The Problem

First, let's understand why this error occurs. In the provided code, the setState() method is called inside the buildlist() method, which is invoked when a button is pressed. However, calling setState() during the build phase triggers a rebuild, leading to an infinite loop and causing the "setState() or markNeedsBuild called during build" error. šŸ˜±

šŸš« Problem 1: The "Horizontal viewport was given unbounded height" Error

The first error you encountered, "Horizontal viewport was given unbounded height," is caused by the ListView.builder() widget inside the build() method. To fix this, simply wrap the ListView.builder() with an Expanded widget, allowing it to take up the remaining available space. šŸ“

Expanded(
  child: ListView.builder(
    ...
  ),
)

By using Expanded, the ListView.builder() will adapt to the available height and prevent the "unbounded height" error. šŸ™Œ

šŸš« Problem 2: The "setState() or markNeedsBuild called during build" Error

The second error, "setState() or markNeedsBuild called during build" occurs due to the same setState() call in the buildlist() method. To resolve this issue, we need to separate the time when setState() is called from the build phase. šŸ”„

To achieve this, we can use a GestureDetector widget with an onTap callback instead of directly calling buildlist() in the onPressed property of the FlatButton. This way, the state will only be updated when the button is tapped, after the build phase is complete. šŸ’”

Here's an example of how you can implement the GestureDetector widget:

GestureDetector(
  onTap: () => buildlist('button' + index.toString()),
  child: FlatButton(
    ...
  ),
)

By implementing the GestureDetector and moving the setState() call out of the build() method, you'll no longer face the "setState() or markNeedsBuild called during build" error. šŸŽ‰

šŸ› ļø Final Code

Here's the updated code with the solutions implemented:

class MyHomePage2 extends State<MyHome> {
  List items = [];

  buildlist(String s) {
    setState(() {
      // Your logic here
    });
  }

  @override
  Widget build(BuildContext context) {
    // Your existing code here
    return Scaffold(
      drawer: drawer,
      appBar: AppBar(
        title: Text('Booze Up'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 4,
              itemBuilder: (BuildContext context, int index) {
                return Column(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () => buildlist('button' + index.toString()),
                      child: FlatButton(
                        child: Image.asset(
                          'images/party.jpg',
                          width: width,
                          height: width,
                        ),
                        onPressed: null,
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          Expanded(
            child: ListView(
              padding: EdgeInsets.fromLTRB(10.0, 10.0, 0.0, 10.0),
              children: items,
              scrollDirection: Axis.vertical,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: null,
        child: Icon(Icons.add),
      ),
    );
  }

  // Your existing code here
}

šŸ“¢ Your Next Steps

Give the updated code a try, and both of the errors should be resolved. šŸ„³ If you encounter any other issues or have any further questions, feel free to ask in the comments below. Our community is always here to help you out. šŸ’¬

Remember, šŸš€ practice makes perfect! Keep exploring Flutter and building amazing apps. And if you found this blog post helpful, don't forget to share it with your fellow developers. Let's spread the knowledge! šŸ˜„

Happy coding! šŸ’»āœØ


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

šŸ”„ šŸ’» šŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! šŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings šŸ’„āœ‚ļø Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide šŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? šŸ¤” Well, my

Matheus Mello
Matheus Mello