【发布时间】:2021-03-29 08:21:33
【问题描述】:
如您所见,我正在尝试在我的 StatelessWidget 中使用我的 StatefulWidget 的函数 addUser。唯一的问题是下面的错误添加HomeWidget(addUser: addUser),: 无法在初始化程序中访问实例成员“addUser”。 你能帮我解决这个问题吗? 非常感谢。
我的 StatefulWidget:
class _HomeStatefulState extends State<HomeStateful> {
void addUser() {
//do something
}
final List<Widget> _children = [
HomeWidget(addUser: addUser),
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: onTabTapped,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text("Home"),
backgroundColor: Colors.blue,
),
]),
);
}
}
StatelessWidget:
class HomeWidget extends StatelessWidget {
const HomeWidget({Key key, @required this.addUser}) : super(key: key);
final VoidCallback addUser;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
SafeArea(
child: Column(
children: [
Padding(
child: FlatButton(
onPressed: addUser,
),
),
],
)),
],
),
);
}
}
【问题讨论】:
-
将
final List<Widget> _children = ...语句移动到build函数中,然后再返回语句