使用BottomNavigationBar小部件时,我创建了一个与主体具有相同类的列表。该类使用有状态小部件,但是当我单击按钮以调用setState()时,另一个对象已受影响。
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new _HomeState();
}
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
List<PlaceHolderView> _children = [
new PlaceHolderView(currentPage: 0,),
new PlaceHolderView(currentPage: 1,),
new PlaceHolderView(currentPage: 2,),
];
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(title: Text('Full Test'),),
body: _children[_currentIndex],
bottomNavigationBar: new BottomNavigationBar(
items: [
new BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text('Home')),
new BottomNavigationBarItem(
icon: Icon(Icons.list), title: Text('Data')),
new BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Profile')),
],
onTap: _changeSelectedView,
currentIndex: _currentIndex,
),
);
}
void _changeSelectedView(int index) {
setState(() {
_currentIndex = index;
});
}
}
这是占位符视图:
class PlaceHolderView extends StatefulWidget {
PlaceHolderView({Key key, this.currentPage}) : super(key: key);
final int currentPage;
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new _PlaceHolderVieWState();
}
}
class _PlaceHolderVieWState extends State<PlaceHolderView> {
String str = 'Click Button';
void _buttonClicked() {
setState(() {
str = 'Button Clicked';
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Center(
child:RaisedButton(onPressed: _buttonClicked, child: Text('${widget.currentPage} page\'s button ${str}'),),
);
}
}
当我单击其中一个页面中的按钮时,其他页面都改变了str。所以我想知道这是怎么发生的以及如何避免这种情况。
答案 0 :(得分:0)
好吧, setState()方法刷新有状态的整个小部件, 如果要在setState()处更改特定窗口小部件的状态,请将其用作有状态,然后在无状态窗口小部件中调用它。