streambuilder is rebuilding again and again when keyboard popup or closes streambuilder is rebuilding again and again when keyboard popup or closes dart dart

streambuilder is rebuilding again and again when keyboard popup or closes


Flutter calls the build() method every time it wants to change anything in the view, and this happens surprisingly often.

You can pass the stream into the stateless widget

 MyApp({Key key, this.stream}) : super(key: key);

Or build the stream in the initState method if the widget is statefull.

@overridevoid initState() {  super.initState();  post = buildStream();}


What @TuanNguyen means by

build the stream in the initState method

is the following, if for you are using Firestore for exemple:

class MyStateFullWidget extends StatefulWidget {  const MyStateFullWidget({Key key}) : super(key: key);  @override  _MyStateFullWidgetState createState() => _MyStateFullWidgetState();}class _MyStateFullWidgetState extends State<MyStateFullWidget> {  Stream _myStream;  @override  void initState() {    super.initState();    _myStream = FirebaseFirestore.instance.collection(myCollection) ... .snapshots();  }  @override  Widget build(BuildContext context) {    return SomeUpperWidget(      child:       StreamBuilder(        stream: _myStream,        builder: (ctx, snap) => ... ,      )    );  }}


I was facing the same issue. I could not find simple alternative to avoid re-rendering without changing much code. So I ended up like this:

So in the Bloc class, first initiated a variable say streamStateIndex = 0;And wherever I am using sink.add(data), I started using

streamStateIndex++;sink.add({"data": data, "streamStateIndex":streamStateIndex});

And initiated another variable lets say localStreamStateIndex = 0; inside Stateful flutter class to compare streamStateIndex from bloc

And used inside StreamBuilder like this:

if(snapshot.hasData){    if(localStreamStateIndex < snapshot.data['streamStateIndex']){        updateLocalState(snapshot.data['data']);        localStreamStateIndex = snapshot.data['streamStateIndex'];     }}