Flutter: How to make a widget disappear after a few seconds?

Issue

I wanted to make my widget disappear after a few seconds, but it keep getting stuck on waiting.

if (unread != 0 && (getMessageObjects.length - count) == unread - 1) {
          _groupedMessages.add(
            FutureBuilder(
              future: Future.delayed(Duration(milliseconds: 500)),
              builder: (c, s) => s.connectionState == ConnectionState.done
                  ? Container(
                      child: Chip(
                        label: Text('Finished'),
                      ),
                    )
                  : Center(
                      child: Chip(
                        label: Text('${unread.toString()} unread messages'),
                      ),
                    ),
            ),
          );
          // reset
        }

The _groupedMessages is a List. I have no idea if there are other ways, but please let me know if there are.

Solution

Your code looks odd but we need to see the rest of the code.

First thought, are you certain that the future isn’t being constantly recreated and hence doesn’t have a chance to complete?

It also seems odd that you are going to show a message indicating the count for 500ms then hide it.

Also why the artificial delay?

I’m guessing you need to fetch the count from a server in which case the future should contain the call to the server and complete when the results are returned.

I would the expect the UI to show a message ‘fetching messages’ and then change to ‘unread messages x’ once the fetch completes.

But these are just guesses given the limited amount of context you have provided.

Answered By – Brett Sutton

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

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