The Mir
The Mir

Reputation: 450

Unable to access fetched data in initState in Flutter

I have class named Cards that has a method getCards that returns back a Future. I use this method to get cards from an endpoint.

Cards:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class Cards {
  String _accessToken;
  String _refreshToken;

  List<dynamic> cardsId = List();

  Future<dynamic> getCards() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    _accessToken = sharedPreferences.getString("access");
    _refreshToken = sharedPreferences.getString("refresh");
    var jsonData;

    var response = await sendRequestToGetCards(
        url: "http://10.0.2.2:8000/accounts/list/", accessToken: _accessToken);
    if (response.statusCode == 200) {
      jsonData = json.decode(utf8.decode(response.bodyBytes));
      return jsonData;
    } else if (response.statusCode == 401) {
      _accessToken = await getNewAccessToken(_refreshToken);
      response = await sendRequestToGetCards(
          url: "http://10.0.2.2:8000/accounts/list/",
          accessToken: _accessToken);
      if (response.statusCode == 200) {
        jsonData = json.decode(utf8.decode(response.bodyBytes));
        return jsonData;
      }
    }
  }

  getNewAccessToken(String refreshToken) async {
    var refreshResponse = await http.post(
        "http://10.0.2.2:8000/users/api/token/refresh/",
        body: {'refresh': refreshToken});
    if (refreshResponse.statusCode == 200) {
      var jsonData = json.decode(refreshResponse.body);
      return jsonData['access'];
    }
  }

  sendRequestToGetCards({String url, String accessToken}) async {
    var response = await http.get(
      url,
      headers: {"Authorization": "Bearer $accessToken"},
    );
    return response;
  }
}

I have an other class called CardData as my Provider data/state:

import 'package:flutter/material.dart';

import '../cards/cards.dart';

class CardData extends ChangeNotifier {
  static Cards cards = Cards();

  Future<dynamic> cardsList = cards.getCards;

}

Which you can see I created an object from Cards to access getCards that makes me able to access the returned Future and saving it in cardsList.

Now in my widget that I used to display all the cards I created a method called addToList to access the Provider data.

I've created some lists to save Widgets to pass them to other Widget later.

List<Widget> cardsList = List();
List<dynamic> cardsId = List();

List<Widget> nonCards = List();
List<dynamic> nonCardsId = List();

addToList() async {
    var jsonData = await Provider.of<CardData>(context).cardsList;
    for (var i = 0, len = jsonData.length; i < len; i++) {
      if(jsonData[i]['account_type'] == "1") {
        cardsList.add(
          BankCard(
            bankName: jsonData[i]['title'],
            colors: [Color(0xFFD00E00), Color(0xFFF44336)],
            cardNumber: jsonData[i]['number'],
            cardDesc: jsonData[i]['description'],
          ),
        );
        cardsId.add(jsonData[i]['id']);
      } else if(jsonData[i]['account_type'] == "2") {
        nonCards.add(
          NonBankCard(
            bankName: jsonData[i]['title'],
            colors: [Color(0xFFFF4B2B), Color(0xFFFDB76C)],
          ),
        );
        nonCardsId.add(jsonData[i]['id']);
      }
    }
  }

But I need to use addToList method in initState as you know but I can't. when I do use it there the app screen will disappears.

Upvotes: 0

Views: 519

Answers (1)

Elad
Elad

Reputation: 971

you should initialize your list at the beginning

  List<Widget> cardsList = new List<Widget>();

Call addToList inside your initState function:

@override
  void initState() {
     addToList();
}

at the end of addToList() put the updated list in setState()

setState(() {
    cardsList = List.from(cardsList);
});

Upvotes: 1

Related Questions