无法根据状态更改页面

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

Flutter新手,我使用底部导航来切换页面内容。基于调试,正在发生设置状态,其中正在捕获正确的索引号并将其分配给_selectedPage变量。然而,一旦我跨过该代码,页面内容保持不变而不改变内容,无论我选择什么图标,都在底部导航中保持选中“Home”图标。

当我从导航栏中选择不同的图标时,我期望有所不同的评论部分。请指教。

import 'package:flutter/material.dart';

class LatestFeed extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => LatestFeedState();
}

class LatestFeedState extends State<LatestFeed>{

  @override
  Widget build(BuildContext context) {

    int _selectedPage = 0;
    List pageOptions = [
      Text('one1', style: TextStyle(fontSize: 36),), // Expecting a change but now it always remains on this data. No change even when set state changes to different index.
      Text('two', style: TextStyle(fontSize: 36),),
      Text('three', style: TextStyle(fontSize: 36),),
      Text('four', style: TextStyle(fontSize: 36),)
    ];

    return MaterialApp(
      home: new Scaffold(
        body: pageOptions[_selectedPage],
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
            items: [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text('Home')
              ),
              BottomNavigationBarItem(
                  icon: Icon(Icons.rss_feed),
                  title: Text('feed')
              ),
              BottomNavigationBarItem(
                  icon: Icon(Icons.featured_play_list),
                  title: Text('list')
              ),
              BottomNavigationBarItem(
                  icon: Icon(Icons.settings),
                  title: Text('settings')
              ),
            ],
            currentIndex: _selectedPage, // expecting different icons to be selected based on this index which is being selected in the set state below. Not seeing any change.
            onTap: (int index){
              setState(() {
                _selectedPage = index; // being assigned correctly yet no effect
              });
            },
        ),
      ),
    );
  }
}
dart flutter
1个回答
1
投票

将_selectPage和pageOptions放在initState中或构建方法之外,以防止在调用setState时重建

int _selectedPage;
List<Widget> pageOptions;
    @override
      void initState() {
        super.initState();
         _selectedPage = 0;
        pageOptions = [
          Text('one1', style: TextStyle(fontSize: 36),), // always remains on this data. No change even when set stae changes to different index.
          Text('two', style: TextStyle(fontSize: 36),),
          Text('three', style: TextStyle(fontSize: 36),),
          Text('four', style: TextStyle(fontSize: 36),)
        ];
      }  

无论何时调用setState,都会有更改导致窗口小部件重建。这意味着将再次调用您的构建方法。当它被调用时,_selectedPage将再次设置为0,pageOptions [0]将始终是所选的窗口小部件。

© www.soinside.com 2019 - 2024. All rights reserved.