如何在没有MaterialPageRoute的情况下传递参数函数setState



我有更新状态的问题。我需要将一个带有setState的函数传递到一个小部件中,但我不知道。问题是我需要传递一个静态函数,而在那里我不能执行setState。我有哪些选项可以修复它?

我的代码

class NavigationBar extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _NavigationBarState();
}
}
class _NavigationBarState extends State<NavigationBar> {
bool showMusicTab = false;
bool openMusicTab = false;
int index = 4;
final List<Widget> screens = [
Home(),
Search(),
AddPost(),
Notifications(),
Profile(showMusicTabAndPlay)
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: screens[index],
persistentFooterButtons: showMusicTab
? <Widget>[
Container(
color: Colors.black,
height: 20,
width: MediaQuery.of(context).size.width,
child: ListTile(
leading: Icon(Icons.favorite_border, color: Colors.white),
title: Center(
child: InkWell(
onTap: () {},
child: Text(
'Break my soul',
style: TextStyle(
color: Colors.white,
fontFamily: kRobotoBold,
fontWeight: FontWeight.bold),
),
),
),
trailing: Icon(
Icons.pause_circle_filled,
color: Colors.white,
),
),
)
]
: null,
bottomNavigationBar: BottomNavigationBar(
currentIndex: index,
onTap: (int index) {
setState(() {
this.index = index;
});
},
type: BottomNavigationBarType.fixed,
showSelectedLabels: false,
showUnselectedLabels: false,
backgroundColor: Colors.black,
items: [
new BottomNavigationBarItem(
icon: new Icon(
Icons.home,
color: index == 0 ? Colors.pinkAccent : Colors.white,
),
title: new Text('Home'),
),
new BottomNavigationBarItem(
icon: new Icon(
Icons.search,
color: index == 1 ? Colors.pinkAccent : Colors.white,
),
title: new Text('Search'),
),
new BottomNavigationBarItem(
icon: new Icon(
Icons.add_circle,
color: index == 2 ? Colors.pinkAccent : Colors.white,
),
title: new Text('Add post'),
),
new BottomNavigationBarItem(
icon: new Icon(
Icons.notifications,
color: index == 3 ? Colors.pinkAccent : Colors.white,
),
title: new Text('Notifications'),
),
new BottomNavigationBarItem(
icon: Icon(
Icons.person,
color: index == 4 ? Colors.pinkAccent : Colors.white,
),
title: Text('Profile'))
],
),
);
}
static void showMusicTabAndPlay() {
setState(() {
showMusicTab = true;
});
}
}

您的问题是,当小部件首次创建时,您正试图通过直接在字段声明处为其分配对象的List来填充screens

class _NavigationBarState extends State<NavigationBar> {
final List<Widget> screens = [
Home(),
Search(),
AddPost(),
Notifications(),
Profile(showMusicTabAndPlay)
];
...
}

当你像这样填充对象时,你只能使用静态字段和方法来填充它。这对showMusicTabAndPlay来说是个问题,因为它调用setState,这是一个实例方法,不能从静态方法调用。

相反,您应该在构造函数或initState方法(建议使用后者(中填充screens

class _NavigationBarState extends State<NavigationBar> {
List<Widget> screens;
@override
void initState() {
super.initState();
screens = [
Home(),
Search(),
AddPost(),
Notifications(),
Profile(showMusicTabAndPlay)
];
}
...
}

有了这个,您现在可以将showMusicTabAndPlay作为实例方法,而不是静态方法,这样错误就会消失。

最新更新