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

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.

Related

How can I access an instance of an object in different classes / pages without a widget tree context?

I am trying to access an instance of an RtcEngine object for AgoraIO from another class/page that doesn't have a widget tree, and therefore no context to refer to with Provider.
First I'm calling initPlatformState() from this class in order to initialize the RtcEngine engine:
class Game extends StatefulWidget {
#override
_GameState createState() => _GameState();
}
class _GameState extends State<Game> implements GameListener {
#override
void initState() {
super.initState();
Agora().initPlatformState(widget.playerId);
}
}
initPlatformState initializes the RtcEngine by creating an instance called engine that I need to use later on to call other methods. This class also contains the method I want to call later using the same instance to adjustVolume...
class Agora {
RtcEngine engine;
// Initialize the agora app
Future<void> initPlatformState(int playerId) async {
RtcEngine engine = await RtcEngine.create(APP_ID);
}
void adjustVolume(int uid, int volume) {
engine.adjustUserPlaybackSignalVolume(uid, volume);
}
}
This is the class that I want to call adjustVolume from. I was considering using Provider to pass the instance to this class but it extends another class and it doesn't have a widget tree with context so I'm not sure how thats possible or if there is a better way.
class Remote extends Component {
final int id;
Remote(this.id);
#override
void update() {
//this is where I'm trying to access the engine instance that was created to call adjustUserPlaybackSignalVolume method
}
}
Any suggestions on how to reuse that instance of "engine" given my situation would be greatly appreciated!

Unable to initialize static member in Dart

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;
}
}

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.

Transfer variable to other class

I am trying to get a list from class to the other. But I want it to only be transferred after it has got a value assigned from a Future. Is there a way to do so (something like a setState method that acts across classes) My code is here:
class Design extends StatefulWidget {
#override
_DesignState createState() => _DesignState();
}
class _DesignState extends State<Design>{
var Data;
#override
void initState() {
super.initState();
comparer().then((List returnedV){
setState(() {
Data = returnedV;
});
});
}
Future<List> compare() async {
...
return dataDevice
}
}
class AboutSheet extends StatefulWidget {
final List Data;
AboutSheet({#required this.Data});
#override
_AboutSheetState createState() => _AboutSheetState();
}
class _AboutSheetState extends State<AboutSheet> {
}
Every time I use the variable Data in the second class it has the value null. I think it's because I have defined it before with the value null and it's pulling that and is not waiting for the future to assign a value to it. I can't think of a workaround. I would really appreciate your help!
What you are referring to is a state management solution. There is a lot of them, with each their pros and cons. I (and the Flutter team) would suggest Provider.
Take a look at this : List of state management approaches

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
}
// ...
}