我从一个有状态的小部件中获得了这段代码,
static String code = '+1';
String phone;
String finalphone = '$code' + '$phone'; =>this declaration brings an error
that 'Only static members can be accessed in initializers'
我应该如何将这两个变量放在一起,以便使我看起来像+1535465345
我正在收集用户信息
//the widget
Widget form() {
return Form(
key: _formKey,
child: TextFormField(
decoration: InputDecoration(
contentPadding: EdgeInsets.all(0.0),
),
style: TextStyle(
letterSpacing: 2.0,
fontSize: 19.0,
fontWeight: FontWeight.bold,
color: Colors.black87),
onSaved: (value) => phone = value, //the (value) here is a
//string which is
//assigned
//to phone variable declared at the top
),
),
);
}
还将电话变量设为静态并打印出串联字符串会带出+1null
答案 0 :(得分:3)
答案 1 :(得分:2)
您需要指定类以访问静态成员
String finalphone = '${MyClass.code}$phone';
答案 2 :(得分:2)
确保在给变量赋值之前使用phone
变量会带来错误,从而引发空引用异常。
无论这里是否有完整的修复,希望它都能起作用:
static String code = '+1';
String phone;
String finalphone = "";
//the widget
Widget form() {
return Form(
key: _formKey,
child: TextFormField(
decoration: InputDecoration(
contentPadding: EdgeInsets.all(0.0),
),
style: TextStyle(
letterSpacing: 2.0,
fontSize: 19.0,
fontWeight: FontWeight.bold,
color: Colors.black87),
onSaved: (value) {phone = value; finalphone = '$code' + '$phone'; }
),
),
);
您可能需要使用
setState
来赋值并重建视图。