我有一个用户类,该类在登录时传递到第二个屏幕。当我调试它时,值出现在第二个屏幕上,但是由于某种原因我无法访问user.firstName。
我在“字符串userFirstName = user.firstName;”上遇到错误错误是说“初始化器中只能访问静态成员”,这是我的新手,请确保我做错了事。
这是有问题的代码:
class HomeMember extends StatelessWidget {
final User user;
formatDate(){
var date =DateTime.now();
var suffix = "th";
var digit = DateTime.now().day % 10;
if ((digit > 0 && digit < 4) && (date.day < 11 || date.day > 13)) {
suffix = ["st", "nd", "rd"][digit - 1];
}
return new DateFormat("EEEE MMMM d'$suffix'").format(DateTime.now());
}
HomeMember({Key key, @required this.user}) : super(key: key);
String userFirstName = user.firstName;
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new LBAppBar().getAppBar(),
drawer: new LBDrawer().getDrawer(),
body: Container(
decoration: BoxDecoration(
gradient: new LinearGradient(
colors: [Color.fromRGBO(1,89,99, 1.0), Colors.grey],
begin: Alignment.bottomLeft,
end: Alignment.topRight
)
),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
Row(
children: [
Container(
margin: EdgeInsets.only(left: 20.0,top: 10.0, bottom: 10.0, right:30.0),
child: Column(
children: <Widget>[
Text("Hi $userFirstName, Today is " + formatDate(), style: new TextStyle( color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 19.0 )),
答案 0 :(得分:1)
我在格式化字符串时犯了一个错误。这是正确的方法:“您好$ {user.firstName},今天是”
答案 1 :(得分:0)
定义一个全局变量来保存应由许多类访问的值,这将确保对该值的任何更改都将反映在您的应用程序中:
String userFirstName ;
class HomeMember extends StatelessWidget {
userFirstName = user.firstName;
}