Home > Back-end >  Data from API takes long time to load onto the emulator in Flutter
Data from API takes long time to load onto the emulator in Flutter

Time:09-21

I am loading a crypto API from Coingecko in a ListView.builder widget.

This is the API: https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false

If I load it for the first time when I launch the emulator, the data shows almost instantly. Which is not bad.

However, if I make edits to my UI and try to do hot reloads, more often than not, it takes awhile for the data to appear on the emulator, approx 1 minutes to 5 minutes. Sometimes, nothing loads onto the screen and I do wonder if it is actually still running behind the scene. This makes it very hard for me to make adjustments/tweaks/design the UI. I will either have to :

  1. Wait for it to appear on screen or

  2. Close the emulator and restart again from the Virtual Device Manager for the data to appear right away on screen.

Is there a way for the data from the API to load faster to make the design experience much smoother? Or am I doing it the wrong way?

FYI, I use Android Studio.

Any help would be much appreciated. Thanks in advance.

The code is as follows:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreen();
}

class _HomeScreenState extends State<HomeScreenScreen> {

  Future<List<Asset>> fetchCoin() async {
    assetList = [];
    final response = await http.get(Uri.parse(
        'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false'));

    if (response.statusCode == 200) {
      List<dynamic> values = [];
      values = json.decode(response.body);
      if (values.length > 0) {
        for (int i = 0; i < values.length; i  ) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            assetList.add(Asset.fromJson(map));
          }
        }
        setState(() {
          assetList;
        });
      }
      return assetList;
    } else {
      throw Exception('Failed to load coins');
    }
  }

  @override
  void initState() {
    fetchCoin();
    Timer.periodic(Duration(seconds: 1), (timer) => fetchCoin());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add Asset', style: TextStyle(color: Colors.black),),
        elevation: 0,
        toolbarHeight: 50,
        backgroundColor: Colors.white,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search, color: Colors.black26),
            onPressed: () {},
          )
        ],
      ),
      body: ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: assetList.length,
        itemBuilder: (context, index) {
          return AssetCryptoCard(
            name: assetList[index].name,
            image: assetList[index].image,
          );
        },
      ),
    );
  }
}

CodePudding user response:

Application doing too much work on main thread. This kind of application should be developed with the help of multi threading concept.so flutter also support multi threading with the help of Isolates. it will be give high performance. it may be helpful below this tutorial

https://www.javatpoint.com/dart-isolates

https://pub.dev/documentation/flutter_isolate/

CodePudding user response:

Code calls the rate limited API at every second. When the rate is exceeded, API stops answering with 200 responses until resumes after a while, when the threshold is reset.

Timer.periodic(Duration(seconds: 1), (timer) => fetchCoin());
  • Related