【问题标题】:How load content of Page just when page shown in screen in flutter当页面在屏幕中显示时如何加载页面内容
【发布时间】:2020-06-12 16:18:15
【问题描述】:

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-05
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      相关资源
      最近更新 更多