Flutter的新手,我正在使用底部导航来切换页面内容。基于调试,将在捕获正确的索引号并将其分配给_selectedPage变量的情况下发生设置状态。但是,一旦我跳过该代码,页面内容将保持不变,而不会更改内容,并且无论我选择哪种图标,“首页”图标在底部导航中均保持选中状态。
注释部分,当我从导航栏中选择其他图标时,它们会有所不同。请指教。
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
});
},
),
),
);
}
}
答案 0 :(得分: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]将始终是选定的小部件。