Unable to initialize static member in Dart - class

I have read similar questions
Error: Only static members can be accessed in initializers what does this mean?
Dart - Only static members can accessed in initializers
But I am still unable to solve the problem.
I am sending Ip object which has a Ip string from one screen to another.
Here is Second screen's widget and state class in short.
class DrawingPage extends StatefulWidget {
Ip ipObj;
// String ipObj;
DrawingPage({Key key, #required this.ipObj});
_DrawingPageState createState() => _DrawingPageState();
}
class _DrawingPageState extends State<DrawingPage> {
final String ip = widget.ipObj.ip; //Error at "widget": Only Static members can be accessed in initializers
}
I have tried
1.Initializer's List.
2.Converting final to static member and then assigning ip value in initState does work.
But the value is set when initState is invoked, but I want to set value before initState.
How should I do it?

There are a number of options here... I'm not sure which one would be best for your case, but I usually use the second one, as I don't like to reference the 'widget' object in the state all the time:
Option 1: convert 'ip' to a field
class _DrawingPageState extends State<DrawingPage> {
String get ip => widget.ipObj.ip;
}
Option 2: pass the ipObj in the constructor of the state:
class DrawingPage extends StatefulWidget {
Ip ipObj;
DrawingPage({Key key, #required this.ipObj});
_DrawingPageState createState() => _DrawingPageState(ipObj);
}
class _DrawingPageState extends State<DrawingPage> {
String ip;
DrawingPageState(Ip ipObj){
ip = ipObj.ip;
}
}

Related

Access variable of a class inside other classes Flutter

I have a class which has variables like this:
class MyDragTarget extends StatefulWidget {
final String assetImage;
final String name;
MyDragTarget(this.name, this.assetImage);
}
EDIT: Sorry for wrong code below. I knew how to use widget.name to get name of the parent. But how can i get name of other class.
Should i use InheritedWidget? To use InheritedWidget must i learn Provider?
I want to access the name and assetImage of MyDragTarget in another class such as:
class Another extends StatefulWidget {
print(MyDragTarget.name);
}
You can use widget.name. For example, if you are trying to access assetImage you can use print('${widget.assetImage}'); Just a side note, this is to access the variables in your StatefulWidget. You can't do it for any class.
you can get using widget
widget.assetImage
wiget.name
print('${wiget.name}');
if you want to use in its create State class, you can access it via widget.assetImage Like
class _MyDragPlayerState extends State<MyDragPlayer> {
...
// print('${widget.assetImage }');
...
}
but if you want to access in other classes than this you can declare variables as static like
class MyDragTarget extends StatefulWidget {
static String assetImage;
static String name;
MyDragTarget(this.name, this.assetImage);
#override
_MyDragTargetState createState() => _MyDragTargetState();
}
and then in other class you can access via
class OtherClass{
...
// print('${MyDragTarget.assetImage }');
...
}
check for null safety first, also read about pros and cons of using static variables.

Flutter: Undefined name Try correcting the name to one that is defined, or defining the name

I am facing a few strange issues with Flutter. I do have very little knowledge about Flutter. I am learning it.
class ViewOtherProfile extends StatefulWidget {
final String userName;
final int points;
const ViewOtherProfile({
#required this.userName,
#required this.points,
});
You can see i am getting userName and Points data as argument.
I want to print this argument in the page. Like this
class _ViewOtherProfileState extends State<ViewOtherProfile> {
..........
void initState(){
print(points);
deviceInfo();
super.initState();
print(userName);
]);
}
............
Now problem is i am getting error.
Undefined name 'userName'.
Try correcting the name to one that is defined, or defining the name.
Any reason why i am getting this error and how i can resolve it.
Thanks to #jamesdlin
I tried to put it like this
print(ViewOtherProfile.userName);
but now i am getting another error.
Instance member 'userName' can't be accessed using static access.
There are two main types of widgets in Flutter. StatelessWidget and StatefullWidget. A StatelessWidget is built only one when the UI builds and is never rebuilt. Meanwhile, a StatefulWidget can be rebuilt every time if a call for setState is made.
Hence, for a StatefulWiget, there is a need to track the state of the class by extending the main class with a State class.
You have to note that the scope of variables in those two types of widgets can vary. For example...
class ExampleStateless extends StatelessWidget {
final String userName;
final int points;
const ExampleStateless({
#required this.userName,
#required this.points,
});
#override
Widget build(BuildContext context){
print(userName); print(points);
return Something();
}
}
Note that for the stateful widget, there are two classes and each class has its scope. The superclass ExampleStateful can share its scope to its subclass _ExampleStatefulState via the widget
class ExampleStateful extends StatefulWidget {
final String userName;
final int points;
Static final string id = "exampleState";
const ExampleStatefull({
#required this.userName,
#required this.points,
});
// scope 1
#override
_ExampleStatefulState createState() => _ExampleStatefulState();
}
class _ExampleStatefulState extends State<ExampleStateful>{
// scope 2
final String userName2 = null;
#override
void initState(){
super.initState();
print(widget.userName);
print(userName2);
print(ExampleStateful.id); // you can do this only if variable is static.
}
}
What is in scope 1 can be accessed in scope 2 via the widget properties. eg print(widget.userName); instead of print(userName);

Flutter Instance member ‘{0}’ can’t be accessed using static access

I am passing variables from one activity to another in flutter but getting the error "Instance member ‘latitude’ can’t be accessed using static access" I need it converted in that block so I can assign it to a static URL.
class Xsecond extends StatefulWidget {
final double latitude;
final double longitude;
Xsecond(this.latitude, this.longitude, {Key key}): super(key: key);
#override
_Xsecond createState() => _Xsecond();
}
class _Xsecond extends State<Xsecond> {
static String lat = Xsecond.latitude.toString(); // Error: Instance member ‘latitude’ can’t be accessed using static access
...
followed by
...
String url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},$lng&radius=$radius&type=restaurant&key=$api';
...
In your code both latitude and longitude are defined as non-static i.e. are instance variables. Which means they can only be called using a class instance.
class _Xsecond extends State<Xsecond> {
final xsecond = Xsecond();
static String lat = xsecond.latitude.toString();
...
Please read the basics of any Object Oriented Programming language e.g. Dart, java, C++
However, in your context the first class is your StatefullWidget. So you can access that by the widget field of your state class.
FIX:
class _Xsecond extends State<Xsecond> {
static String lat = widget.latitude.toString();
...
This error occurs if you use non-static variable like static. Let's take a look at this example:
class MyPage extends StatefulWidget {
final foo = Foo();
// ...
}
class _MyPageState extends State<MyPage> {
final newFoo = MyPage.foo; // Error
// ...
}
MyPage.foo isn't a static member but you are using if it was.
To solve this issue, you can either make the variable static
static final foo = Foo();
or
Use widget variable to get hold of the underlying variable.
class _MyPageState extends State<MyPage> {
#override
void initState() {
super.initState();
final newFoo = widget.foo; // No Error
}
// ...
}

How to access it's static constant from instance of an object?

I have an object that has static constant which I need to reach from its instance.
class ChatsScreen extends StatefulWidget {
var arguments;
static const name = ADatas.chatRoute;
ChatsScreen(this.arguments);
createState() => ChatsScreenState();
}
In above class' State object, I want to call static const name. Above class' State object's code:
class ChatsScreenState extends State<ChatsScreen> with RouteHelper{
String userName = "";
var textEditingController = TextEditingController();
#override
void initState() {
getRouteName(widget); //=> as I understand and see on the VSCode, its the ChatsScreen object.
super.initState();
}
}
I'm trying to implement an interface so I don't know the actually class name while writing the interface. And I thought that I can reach its static constant if I know its actual class. And I wrote something like this but it seems not to be possible. I guess I have a misunderstanding.
class RouteHelper{
String getRouteName(dynamic instance){
if(instance is StatefulWidget){
return instance.runtimeType.name; // => !!!
}
}
}
Note: I'm not trying to get the route name in actual. It's just a concept that i used in this question, so please don't refer better way to get the route name in flutter.
You can't do it like that, people have talked about this in this issue.
However you can kinda do it using class members and typing system.
abstract class Routed {
String getClassRoute();
}
class ChatsScreen extends StatefulWidget implements Routed {
var arguments;
static const name = "myexampleroutename";
ChatsScreen(this.arguments);
createState() => ChatsScreenState();
#override
String getClassRoute() {
return ChatsScreen.name;
}
}
class RouteHelper {
String getRouteName(Routed instance) {
return instance.getClassRoute();
}
}
I said you can't, but with dart:mirrors it is possible, however it is banned on Flutter packages. There is reflectable package that tries to fix that using code generation, but I am not aware of it's status/reliability.

Using argument in initializer list with flutter

I want to make a data list page. It needs a reference based on user id passed by argument. However, the argument can't be accessed because it is not static.
I tried to pass reference itself by argument. But it also falls into the same problem.
class DataViewHome extends StatefulWidget{
final String userId;
DataViewHome({this.userId});
#override
State<StatefulWidget> createState() => DataViewHomeState();
}
class DataViewHomeState extends State<DataViewHome>{
final dataReference = FirebaseDatabase.instance.reference().child("users").child(widget.userId);
List<String> dataList = new List();
StreamSubscription<Event> _onDataAddedSubscription;
DataViewHomeState(){
_onDataAddedSubscription = dataReference.onChildAdded.listen(_onDataAdded);
}
_onDataAdded(Event event){
setState(() {
dataList.add(event.snapshot.value);
});
}
}