我在layoutbuilder中有一个页面视图来获取小部件的大小。
因为它取决于小部件的大小,我不知道在构建小部件之前会有多少页。所以我在layoutbuilder中添加了futurebuilder,所以页面的数量可以异步计算。这是我的代码,但它在ConnectionState.Waiting中无限期地等待。
代码中的问题是什么以及如何解决?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: ScrollableTabsDemo());
  }
}

class _Page {
  const _Page({this.icon, this.text});
  final IconData icon;
  final String text;
}

const List<_Page> _allPages = <_Page>[
  _Page(text: 'tab 1'),
  _Page(text: 'tab 2'),
  _Page(text: 'tab 3'),
];

class ScrollableTabsDemo extends StatefulWidget {
  static const String routeName = '/material/scrollable-tabs';

  @override
  ScrollableTabsDemoState createState() => ScrollableTabsDemoState();
}

class ScrollableTabsDemoState extends State<ScrollableTabsDemo>
    with SingleTickerProviderStateMixin {
  TabController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TabController(vsync: this, length: _allPages.length);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Color iconColor = Theme.of(context).accentColor;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Scrollable tabs'),
        bottom: TabBar(
          controller: _controller,
          isScrollable: true,
          tabs: _allPages.map<Tab>((_Page page) {
            return Tab(text: page.text);
          }).toList(),
        ),
      ),
      body: TabBarView(
        controller: _controller,
        children: _allPages.map<Widget>((_Page page) {
          return SafeArea(
            top: false,
            bottom: false,
            child: LayoutBuilder(builder: (context, constraints) {
              return FutureBuilder<int>(
                  future: getPageCount(),
                  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                        print("none ${snapshot.data}");
                        return Text('none');
                      case ConnectionState.active:
                        print("active ${snapshot.data}");
                        return Text('active');
                      case ConnectionState.waiting:
                        print("waiting ${snapshot.data}");
                        return Center(child: CircularProgressIndicator());
                      case ConnectionState.done:
                        print("done ${snapshot.data}");
                        return buildPageView(snapshot.data);
                    }
                  });
            }),
          );
        }).toList(),
      ),
    );
  }

  Future<int> getPageCount() => Future.delayed(Duration(seconds: 3), () => 5);

  Widget buildPageView(int pageCount) {
    return PageView.builder(
      itemBuilder: (context, position) {
        return Container(child: Center(child: Text(position.toString())));
      },
      itemCount: pageCount,
    );
  }
}

最佳答案

FutureBuilder的文档说明您不应在每次构建时创建未来:https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
要么在字段初始值设定项中运行getPageCount,要么准备一个类似于initState的有状态小部件,该小部件需要一个未来的创建函数并在它自己的FutureBuilder中调用该函数。
编辑:
使用此帮助程序,您可以自动缓存将来的内容

class CachingFutureBuilder<T> extends StatefulWidget {
  final Future<T> Function() futureFactory;
  final AsyncWidgetBuilder<T> builder;

  const CachingFutureBuilder(
      {Key key, @required this.futureFactory, @required this.builder})
      : super(key: key);
  @override
  _CachingFutureBuilderState createState() => _CachingFutureBuilderState<T>();
}

class _CachingFutureBuilderState<T> extends State<CachingFutureBuilder<T>> {
  Future<T> _future;

  @override
  void initState() {
    _future = widget.futureFactory();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<T>(
      future: _future,
      builder: widget.builder,
    );
  }
}

如果getpagecount需要输入大小,那么可以像下面的代码那样使用这个助手小部件。诀窍是使用valuekey,以便flutter知道如何控制cachingfuturebuilder。确保你没有任何大小变化的动画,因为它会导致未来重新加载到每一帧。
class ScrollableTabsDemo extends StatelessWidget {
  Future<int> getPageCount(Size size) {
    return Future.value(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: LayoutBuilder(
          builder: (context, constraints) {
            final size = Size(constraints.maxHeight, constraints.maxWidth);
            return CachingFutureBuilder<int>(
              key: ValueKey(size),
              futureFactory: () => getPageCount(size),
              builder: (context, snapshot) {
                return Text(snapshot.toString());
              },
            );
          },
        ),
      ),
    );
  }
}

关于layout - 当LayoutBuilder里面的FutureBuilder时, flutter 无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57148810/

10-13 01:58