基于Flutter中的当前状态显示小组件

问题描述 投票:-2回答:1

我的基本目的是根据我当前的状态显示一个小部件。假设当用户点击一个按钮时,我使用setState()方法将currentPage的值设置为2

onTabChangedListener: (position, title, color) {
       setState(() {
         currentPage = position;
...

当它是2时,我想显示以下小部件而不是当前正在显示的小部件。我尝试过if/else案件,但似乎并不是这样。我也已经过了这个和这个,但我不清楚实现。我理解有状态小部件是如何工作的 - 只需要一个与我的问题类似的代码示例。

// Widget I want to display when currentPage state is changed to 2.

  Widget _buildContent() {
    return Positioned(
      bottom: 50,
      left: 25,
      right: 25,
      child: Container(
        color: Theme.of(context).backgroundColor,
        child: Column(
          children: <Widget>[
//            _buildTextField("Some Text"),
            _buildLoginButton(),
            SizedBox(height: 20),
            RichText(
              text: TextSpan(
                text: "Some Text",
                style: TextStyle(
                  fontSize: 10.5,
                  fontWeight: FontWeight.w300,
                  letterSpacing: 1,
                ),
                children: [
                  TextSpan(
                    text: "Another Text",
                    style: TextStyle(
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

注意:我当前代码的整页是available here

flutter flutter-layout
1个回答
0
投票

这是我在我的代码中用来做的事情。使用Stack Widget将您要显示的所有页面放在Offstage中。如果后台条件为真,Offstage小部件将隐藏(使其“在舞台上”)。

Stack(
          children: <Widget>[
            Offstage(
              offstage: 0 != _currentBottomBarIndex,
              child: PageOne(),
            ),
            Offstage(
              offstage: 1 != _currentBottomBarIndex,
              child: PageTwo(),
            ),
            Offstage(
              offstage: 2 != _currentBottomBarIndex,
              child: PageThree(),
            ),
            Offstage(
              offstage: 3 != _currentBottomBarIndex,
              child: PageFour(),
            ),
          ],
        ),
© www.soinside.com 2019 - 2024. All rights reserved.