RefreshIndicator内的StreamBuilder多次渲染子小部件,如何避免?

时间:2019-06-22 06:25:34

标签: flutter

当我将StreamBuilder放在RefreshIndicator中时,它通过滚动动作多次渲染小部件。我想避免很多事情,因为StreamBuilder中的图表会进行多次动画处理。

我在以下环境中进行了测试。

$ 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)

output

@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');
                },
              ),
        ),
      ),
    ),
  );
}

我想在StreamBuilder内放置一些RefreshIndicator,而无需进行多次渲染。

1 个答案:

答案 0 :(得分:0)

似乎StreamBuilder在流上重新订阅并触发重新渲染。 将其与RefreshIndicator交换有助于:

  @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'),
                  );
                },
              ),
            );
          },
        ),
      ),
    );
  }
相关问题