登录到我的应用程序后,我可以像这样将用户传递到我的Home小部件...
Future checkAuth(BuildContext context) async {
FirebaseUser user = await _auth.currentUser();
if (user != null) {
print("Already singed-in with ${user.email}");
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => Home(user)));
}
}
在Home小部件中,我采用这样的论点编辑如果我将我的tabs
移至Build中,那将不起作用。也许是因为我使用底部导航?
class Home extends StatefulWidget {
final FirebaseUser user;
Home(this.user, {Key key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
final tabs = [
Container(
child: FirestoreSlideshow(),
),
Container(
child: ProfilePage(widget.user), //Got an error on this line
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: tabs[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
selectedFontSize: 15,
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
size: 28.0,
),
title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(
Icons.account_circle,
size: 28.0,
),
title: Text('Profile'),
),
],
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
}
并且在ProfilePage小部件中,就像在Home中一样接受参数
class ProfilePage extends StatefulWidget {
final FirebaseUser user;
ProfilePage(this.user, {Key key}) : super(key: key);
@override
_ProfilePage createState() => _ProfilePage();
}
但是我一直收到此错误
Only static members can be accessed in initializers.
我尝试解决了一段时间,但似乎没有任何帖子可以回答我的问题。我怎样才能解决这个问题?预先感谢。
您必须在构建方法中调用“ ProfilePage(widget.user)”。您不能像在这里那样在变量声明中访问用户变量:
final tabs = [
Container(
child: FirestoreSlideshow(),
),
Container(
child: ProfilePage(widget.user), //Got an error on this line
)
];
执行:
Widget build(BuildContext context){
return Container(
child: ProfilePage(widget.user),
);
}
您必须在初始状态下使用widget.user。
var tabs;
@override
void initState() {
super.initState();
tabs = [
Container(
child: FirestoreSlideshow(),
),
Container(
child: ProfilePage(widget.user), //Got an error on this line
)
];
}
传递诸如User对象之类的东西,通常整个应用程序都应该注意这一点,但这不是最好的主意。您应该研究一种更具结构性的解决方案,我建议使用提供者模式。通过应用中的任何小部件使用户可访问。
Jeff Delaney(Fireship.io)上有一个很棒的视频,您可能想看看。