Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

streambuilder is rebuilding again and again when keyboard popup or closes

Tags:

flutter

dart

Here I was stuck in a problem. I have a column of widgets with a stream builder and a text field. When i try to input some text, the keyboard pops up and then the stream builder rebuilds again or when the keyboard closes, the stream builder rebuilds again. As i am building a chat screen, I don't want to rebuild the stream builder again as it increases in number of reads.

Any sort of suggestions helpful.

like image 411
Saikumarreddy atluri Avatar asked Feb 21 '19 06:02

Saikumarreddy atluri


2 Answers

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.

@override
void initState() {
  super.initState();
  post = buildStream();
}
like image 156
Tuan Nguyen Avatar answered Oct 24 '22 07:10

Tuan Nguyen


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) => ... ,
      )
    );
  }
}
like image 2
Jerbs Avatar answered Oct 24 '22 06:10

Jerbs