Reputation: 3734
I have this code from a stateful widget which looks like
static String code = '+1';
String phone;
String finalphone = '$code' + '$phone'; =>this declaration brings an error
that 'Only static members can be accessed in initializers'
How am I supposed to bring the two variables together so that i have something that looks like +1535465345
i am collecting user information
//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
),
),
);
}
also making the phone variable static and printing out the concatenated string brings out +1null
Upvotes: 5
Views: 12733
Reputation: 21748
Instead of having a field
, you can have a getter
like
String get finalphone => '$code' + '$phone';
Refer this answer
Upvotes: 6
Reputation: 176
sure it will bring an error you use the phone
variable before give it a value so it will fire null reference exception .
whatever here is a complete fix hope it will work :
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'; }
),
),
);
you may need to use
setState
to asign value and rebuild the view .
Upvotes: 2
Reputation: 277167
You need to specify the class to access static members
String finalphone = '${MyClass.code}$phone';
Upvotes: 6