0

I need to get some information from an endpoint. I have this method:

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

addToList() async {
    var jsonData = await Provider.of<CardData>(context).cardsList;
    print(jsonData);
    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']);
      }
    }
  }

and a class as provider data called CardData:

import 'package:flutter/material.dart';

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

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

  Future<dynamic> cardsList = cards.getCards();
}

and a class called Card to send request and doing all other stuff:

import 'dart:convert';

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

class Cards {
  String _accessToken;
  String _refreshToken;

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

But when I call addToList method in initState to retrieve data before build method, the main UI disappears.

What's wrong with it?

The Mir
  • 400
  • 1
  • 8
  • 17

1 Answers1

0

You can call async function in the initState, but as it itself is not an async function it will not wait for futures to complete before moving on to the build method, which is why your UI disappears because it is building with no data so there are no cards. I would suggest using a FutureBuilder in your build method to build when the async function returns.

Jwildsmith
  • 1,015
  • 2
  • 9
  • 15