0

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 ??

54V4G3208
  • 47
  • 2
  • 9
  • Can you provide the full class? – LMech May 03 '22 at 08:07
  • updated the code please check @LMech – 54V4G3208 May 03 '22 at 08:16
  • Two problems: 1. [Error: The instance member ... can't be accessed in an initializer](https://stackoverflow.com/q/65601214/) 2. The compiler lets you get away with it because you're dealing with a `dynamic` type, but `media['url']` could potentially be `null` (https://dart.dev/null-safety/understanding-null-safety#the-map-index-operator-is-nullable). – jamesdlin May 03 '22 at 08:52

2 Answers2

0

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.

Klaus Wong
  • 59
  • 2
0

try

late String myUrl;

void  _location(dynamic media){
  myUrl =  media['url'];
  }

_location(media);
LMech
  • 150
  • 1
  • 9
  • I'm getting an error " The name '_location' is already defined. Try renaming one of the declarations" on _location(media) – 54V4G3208 May 03 '22 at 08:34
  • ohh maybe location is a reserved word try other name, it's a setter try setLoc() or chek if _location already defined. – LMech May 03 '22 at 08:36
  • I had to make class _HomeState abstract and change the name of _location method , no more errors. Thanks – 54V4G3208 May 03 '22 at 08:44