简体   繁体   中英

Flutter : Unable to fetch json file data from an api

Hello Everyone I am new to flutter during practicing While trying to fetch JSON data from an api I am unable to complete the operation and receiving the below mentioned error. I have attached my entire program and error notification for your suggestions.

What this program is about?

I am trying to fetch the cryptocurrency price details from an api and trying to display the few details of that website in my app. while doing that the data type which i mentioned in the code creating some error and i tried to change the data type and other things but still it is not solved.

main.dart

import 'package:flutter/material.dart';
import 'package:fluttercrypto/home_page.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

void main() async {
  List currencies = await getCurrency();
  print(currencies);
  runApp(MyApp(currencies));
}

class MyApp extends StatelessWidget {
  final List _currencies;
  MyApp(this._currencies); // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: HomePage(_currencies),
    );
  }
}

Future<List> getCurrency() async {
  String cryptoUrl =
      "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids";
  http.Response response = await http.get(Uri.parse(cryptoUrl));
  return jsonDecode(response.body);
}
'''

**homepage.dart**

'''import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  final List currencies;
  HomePage(this.currencies);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List currencies;
  final List<MaterialColor> _colors = [Colors.blue, Colors.indigo, Colors.red];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Crypto Tracker"),
      ),
      body: cryptoWidget(),
    );
  }

  Widget cryptoWidget() {
    return Container(
      child: Column(
        children: [
          Flexible(
            child: ListView.builder(
              itemCount: widget.currencies.length,
              itemBuilder: (BuildContext context, int index) {
                final Map currency = widget.currencies[index];
                final MaterialColor color = _colors[index % _colors.length];
                return _getListItemUi(currency, color);
              },
            ),
          ),
        ],
      ),
    );
  }

  ListTile _getListItemUi(Map currency, MaterialColor color) {
    return ListTile(
      leading: CircleAvatar(
        backgroundColor: color,
        child: Text(currency['name'][0]),
      ),
      title: Text(
        currency['name'],
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: _getSubtitleText(
          currency['current_price'], currency['price_change_24h']),
      isThreeLine: true,
    );
  }

  Widget _getSubtitleText(int priceUSD, String percentageChange) {
    TextSpan priceTextWidget = new TextSpan(
        text: "\$$priceUSD\n", style: TextStyle(color: Colors.black));
    String percentageChangeText = "24 hour : $percentageChange%";
    TextSpan percentageChangeTextWidget;
    if (double.parse(percentageChange) > 0) {
      percentageChangeTextWidget = TextSpan(
        text: percentageChangeText,
        style: TextStyle(color: Colors.green),
      );
    } else {
      percentageChangeTextWidget = TextSpan(
        text: percentageChangeText,
        style: TextStyle(color: Colors.red),
      );
    }

    return RichText(
      text: TextSpan(children: [priceTextWidget, percentageChangeTextWidget]),
    );
  }
}'''


**ERROR**
'''
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'double' is not a subtype of type 'String'

When the exception was thrown, this was the stack: 
#0      _HomePageState._getListItemUi (package:fluttercrypto/home_page.dart:54:46)
#1      _HomePageState.cryptoWidget.<anonymous closure> (package:fluttercrypto/home_page.dart:34:24)
#2      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22)
#3      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1201:28)
#4      SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1214:55)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'double' is not a subtype of type 'String'

When the exception was thrown, this was the stack: 
#0      _HomePageState._getListItemUi (package:fluttercrypto/home_page.dart:54:46)
#1      _HomePageState.cryptoWidget.<anonymous closure> (package:fluttercrypto/home_page.dart:34:24)
#2      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22)
#3      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1201:28)
#4      SliverMultiBoxAdaptorElement.performRebuild.processElement `enter code here`(package:flutter/src/widgets/sliver.dart:1145:67)
====================================================================================================
'''

It's probably because currency['price_change_24h'] isn't a string. When you pass it into _getSubtitleText do currency['price_change_24h'].toString() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM