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
}
// ...
}
Related
Having abstract class with methods that should be defined in multiple concrete class. For simplicity sake, here is an example:
abstract class MyAbstractClass extends StatelessWidget{
const MyAbstractClass ({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text(abstractMethod().toString());
}
int _abstractMethod();
}
class MyConcreteClass1 extends MyAbstractClass {
#override
int _abstractMethod() {
return 42;
}
}
class MyConcreteClass2 extends MyAbstractClass {
#override
int _abstractMethod() {
return 66;
}
}
now when I try to call MyConcreteClass1 or MyConcreteClass2 it gives me the error below:
'MyConcreteClass1' has no instance method '_abstractMethod'
How to call MyConcreteClass1 or MyConcreteClass2 within my screen?
Note that it will work if I called and instance of it like below:
MyConcreteClass1 c = MyConcreteClass1();
int value = c._abstractMethod();
but it should have been called by build method in abstract class, right?
Well, here is an advice for whoever faces this issue:
DON'T use a leading underscore for identifiers that aren’t private.
as this link explains in dart leading underscore in an identifier to mark members and top-level declarations as private. for that it cannot be overridden within inherited classes.
I'm trying to store the result of a method in a string , but i get errors
String _location(dynamic media){
return media['url'];
}
String myUrl = _location(media);
full class
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<List<dynamic>> fetchMedia() async {
final result = await http
.get(Uri.parse('https://iptv-
org.github.io/api/streams.json'));
return json.decode(result.body);
}
String _location(dynamic media) {
return media['url'];
}
String myUrl = _location(media);
...
}
The error says The instance member '_location' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
How can i do this ??
The problem is that I did not find that you have defined and inited the variable called media. You had defined a private function called _location it was fine, but when you were using this function you are passing an undefined and un-inited variable called media.
try
late String myUrl;
void _location(dynamic media){
myUrl = media['url'];
}
_location(media);
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;
}
}
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.
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);
});
}
}