0

Here I have attached an API response parsing model. Which I need do more refactoring by dividing the category , country and apikey. I have created a variable as apikey and assigned near to the apikey string. but the error shown as:

code

class ApiServiceBusiness {

  final category1 = "";
  
  final apiKey = "df892d97b60e454db3f5ba14f4a4b12d";

  dynamic endPointUrla = Uri.parse("https://newsapi.org/v2/top-headlines?country=gb&category=business&apiKey=$apiKey");

  Future<List<Article>> getArticle() async {
    Response res1 = await get(endPointUrla);

    if (res1.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(res1.body);

      List<dynamic> body = json['articles'];

      List<Article> articlesBusiness = body.map((dynamic  item) => Article.fromJson(item)).toList();
      
      return articlesBusiness;
    } else {
      throw ("Can't get the articles");
    }
  }
}

error: The instance member 'apiKey' can't be accessed in an initializer.

how to refactor the apikey, category and courtry each by each string. Thank You.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Learning Curious
  • 101
  • 1
  • 1
  • 5

2 Answers2

1

Make apiKey static like this:

static final apiKey = "df892d97b60e454db3f5ba14f4a4b12d";

you only allow use static variable in initializer.

eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
1

You can use late

late dynamic endPointUrla = Uri.parse(...)

More about late keyword with declaration

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56