0

I have a TextField within StreamBuilder that listens to BehaviorSubject stream. When snapshot has error, the errorText displays it.

The problem is when TextField is scrolled out of visible area and scrolled back in the StreamBuilder rebuilds but error text is gone because this time snapshot.hasError is false.

How to maintain the error?

temirbek
  • 1,415
  • 1
  • 14
  • 27

1 Answers1

2

You might want to store the error in a String variable of you StatefulWidget.
Once you are ready to clear the error (f.ex. a user presses a clear button) you simple set this variable to null.

String errorMsg;

StreamBuilder(
  stream: myStream,
  builder: (BuildContext context, snapshot) {

    if (snapshot.hasError) {
      errorMsg = snapshot.error.toString();
    }

    if (errorMsg != null) {
      return Text(errorMsg);
    }

    return new Text(
      snapshot.data.toString(),
    );
  },
)
Robin Reiter
  • 2,281
  • 15
  • 24
  • Thanks, it works. I faced another problem: If the error was sinked before the streamBuilder was built and then when it eventually builds the error doesn't come. Do you have any idea? – temirbek Apr 11 '19 at 05:21
  • Where exactly are you placing your StreamBuilder? Maybe within another Builder of some sort? What you can always do is have multiple instances of a StreamBuilder for the same stream. You could instantiate this builder somewhere else (where it does not rebuild from the outside so often) just to populate the `errorMsg` – Robin Reiter Apr 11 '19 at 05:25
  • I'm building a form screen that is ListView of StreamBuilders, so when 'Submit' button is hit the validator sinks error to the fields that were not filled and they show error text. So at the moment of clicking the submit button not all fields are drawn on screen, and when user scrolls down the fields get drawn but with no error messages. – temirbek Apr 11 '19 at 06:43
  • I see. Bug I guess you might want to create a new question for that since the original question is solved. This way other people with similar problems can easily find solutions. – Robin Reiter Apr 11 '19 at 06:45