问题
When I put StreamBuilder in RefreshIndicator, it render widgets many times with scroll actions. I want to avoid many it because Charts inside StreamBuilder animate many times.
I tested with following environment.
$ flutter doctor -v
[✓] Flutter (Channel stable, v1.2.1, on Mac OS X 10.13.6 17G5019, locale en-JP)
• Flutter version 1.2.1 at /Users/matsue/work/flutter/flutter_macos_v1.0.0-stable
• Framework revision 8661d8aecd (4 weeks ago), 2019-02-14 19:19:53 -0800
• Engine revision 3757390fa4
• Dart version 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: NestedScrollView(
headerSliverBuilder: (context, innerBoxScrolled) => [
const SliverAppBar(
title: Text('Title'),
),
],
body: RefreshIndicator(
onRefresh: () async {
print('Will refresh');
await Future<void>.delayed(Duration(seconds: 2));
print('Did refresh');
},
child: StreamBuilder(
stream: _streamController.stream,
builder: (context, snapshot) => ListView.builder(
itemCount: 30,
itemBuilder: (context, index) {
print('Render $index');
return Text('index $index');
},
),
),
),
),
);
}
I want to put some StreamBuilder inside RefreshIndicator without widgets rendering many times.
回答1:
It looks like StreamBuilder re-subscribes on the stream and triggers re-rendering. Swapping it with RefreshIndicator helps:
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: NestedScrollView(
headerSliverBuilder: (context, innerBoxScrolled) => [
const SliverAppBar(
title: Text('Title'),
),
],
body: StreamBuilder(
key: streamBuilderKey,
stream: _streamController.stream,
builder: (context, snapshot) {
print(snapshot.connectionState);
return RefreshIndicator(
onRefresh: () async {
print('Will refresh');
await Future<void>.delayed(Duration(seconds: 2));
_streamController.add(null);
print('Did refresh');
},
child: ListView.builder(
itemCount: 30,
itemBuilder: (context, index) {
print('Render $index');
return Text(
'index $index',
key: Key('$index'),
);
},
),
);
},
),
),
);
}
来源:https://stackoverflow.com/questions/56713145/streambuilder-inside-refreshindicator-render-child-widget-many-times-how-to-avo