当页面在屏幕中颤动显示时如何加载页面内容

时间:2020-06-12 16:18:15

标签: flutter dart

这里我有 bottomNavigationBar 在页面之间移动,所以当加载主页时,所有类都将加载并运行 initState ,但是在 initState 中, http请求获取数据;所以当我第一次显示主页时所有的HTTP请求都将运行... 我仅在用户滑动到该页面时才需要运行该页面的http请求


class Home extends StatefulWidget {
  const Home({Key key}) : super(key: key);

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

class _HomeState extends State<Home> {
  int _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: IndexedStack(
          index: _currentIndex,
          children: [
            Partner(),
            Partners(),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
            title: Text('Partner'),
          ),
          BottomNavigationBarItem(
            title: Text('Partners'),
          ),
        ],
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以改为使用TabBarView,如下所示:

class _HomeState extends State<Home> with SingleTickerProviderStateMixin { // necessary
  TabController _tabController;

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

    @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TabBarView(
        controller: _tabController,
        children: <Widget>[Partner(),Partners()],
        physics: NeverScrollableScrollPhysics(),
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (int index) {
          _tabController.animateTo(index);
        },
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
            title: Text('Partner'),
          ),
          BottomNavigationBarItem(
            title: Text('Partners'),
          ),
        ],
      ),
    );
  }

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