首页 > 解决方案 > 当页面在屏幕中显示时如何加载页面内容

问题描述

在这里,我有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'),
          ),
        ],
      ),
    );
  }
}

标签: flutterdart

解决方案


您可以改用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();
  }



推荐阅读