0

I tried getting input(string) from the user using textfield, adding the input in stream, and printing the string on a different screen, but instead of the string stream builder is printing null, I understood, it's because stream doesn't have any data. But I added data in stream once the user types out something in textfield and hit save.How do I love this

Stream

StreamController NameStream = StreamController.broadcast();

Adding data to stream

textField()
textbuttion(
 onPressed: () {
                  addNStream() {
                    NameStream.sink.add(TextController);
                  }

                  setState(() {
                    addNStream();
                  });

)

Printing data in different screen

Scaffold(
  body: Container(
      child: StreamBuilder(
    stream: NameStream.stream,
    builder: (context, snapshot) {
      return Center(
        child: Text(
          snapshot.data.toString(),
          style: const TextStyle(fontSize: 40),
        ),
      );
    },
  )
  ),
)
17
  • you need to setup StreamBuilder.initialData or check snapshot.connectionState / snapshot.hasData (see StreamBuilder official docs - they have some examples on how to do that) Commented Mar 26, 2022 at 6:53
  • I used snapshot.hasData , it printed, no data in stream Commented Mar 26, 2022 at 6:57
  • post your code then Commented Mar 26, 2022 at 6:58
  • I did, in question section Commented Mar 26, 2022 at 8:02
  • i dont see any snapshot.hasData Commented Mar 26, 2022 at 8:04

2 Answers 2

2

Looks like you're using a broadcast stream. Items added to a broadcast stream when nothing is listening are silently discarded.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you please explain it with code
1

when you are using broadcast() your StreamBuilder don't listen to the data in the NameStream.stream in the initialization.

because the NameStream.stream doesn't have any listeners so StreamBuilder assume that the is no data so he doesn't check, this is the reason for the null.

to solve the problem you need to add listener (initSatate) before you add the event to the stream this will allow StreamBuilder to recognize that there is data in the stream.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.