Ошибка noSuchMethod: ‘[]’ Динамический вызов null, перенастроенный из api приложения Flutter

# #api #flutter #google-cloud-firestore #coingecko

Вопрос:

Я пытаюсь вызвать этот api, чтобы получить последние цены на монеты, он не выводил цены и продолжал возвращать эту ошибку.

Ошибка

 NoSuchMethodError: '[]'
Dynamic call of null.
Receiver: null
Arguments: ["current_price"]
Error: Unexpected null value.
    at Object.throw_ [as throw] (http://localhost:49218/dart_sdk.js:5041:11)
    at Object.nullCheck (http://localhost:49218/dart_sdk.js:5366:30)
    at home_view._HomeState.new.getValues (http://localhost:49218/packages/cryptoapp/christdoes/ui/home_view.dart.lib.js:713:29)
    at getValues.next (<anonymous>)
    at http://localhost:49218/dart_sdk.js:37403:33
    at _RootZone.runUnary (http://localhost:49218/dart_sdk.js:37274:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:49218/dart_sdk.js:32530:29)
    at handleValueCallback (http://localhost:49218/dart_sdk.js:33057:49)
    at Function._propagateToListeners (http://localhost:49218/dart_sdk.js:33095:17)
    at _Future.new.[_completeWithValue] (http://localhost:49218/dart_sdk.js:32943:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:49218/dart_sdk.js:32964:35)
    at Object._microtaskLoop (http://localhost:49218/dart_sdk.js:37526:13)
    at _startMicrotaskLoop (http://localhost:49218/dart_sdk.js:37532:13)
    at http://localhost:49218/dart_sdk.js:33303:9
 

Это api_method

 //https://api.coingecko.com/api/v3/coins
import 'package:http/http.dart' as http;
import 'dart:convert';

Future<double?> getPrice( String id ) async {
  try{
    var url = Uri.parse("https://api.coingecko.com/api/v3/coins"  id );
    var response = await http.get(url);
    var json = jsonDecode(response.body);
    var value = json["market_data"]["current_price"]["usd"].toString();
    print(value);
    return double.parse(value);
  } catch( error ){
    print(error);
  }
}
 

Это код, отображающий его в пользовательском интерфейсе

 import 'dart:html';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cryptoapp/christdoes/net/api_methods.dart';
import 'package:cryptoapp/christdoes/net/flutterfire.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import 'add_view.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  double bitcoin = 0.0;
  double ethereum = 0.0;
  double tether = 0.0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    getValues();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    getValue( String id, double amount ) {
      if( id == 'bitcoin' ){
        return bitcoin * amount;
      } else if( id == 'ethereum' ){
        return ethereum * amount;
      } else{
        return tether * amount;
      }
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration( color: Colors.white ),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Center( child: StreamBuilder(
            stream: FirebaseFirestore.instance.collection('Users').doc(FirebaseAuth.instance.currentUser!.uid).collection('Coins').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if( !snapshot.hasData ){
              return Center( child: CircularProgressIndicator(), );
            }

            return ListView( children: snapshot.data!.docs.map( (document) {
              return Padding(
                padding: const EdgeInsets.only(top: 5.0, left: 15.0, right: 15.0),
                child: Container( width: MediaQuery.of(context).size.width / 1.3, height: MediaQuery.of(context).size.height / 12,
                  decoration: BoxDecoration( borderRadius: BorderRadius.circular(15.0), color: Colors.blueAccent ),
                  child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox( width: 5.0),
                    Text('Coin Name: ${ document.id }', style: TextStyle(color: Colors.white, fontSize: 18.0),),
                    Text('Amount Owned: ${ getValue(document.id, document.get('Amount')).toStringAsFixed(2)}',
                    style: TextStyle(color: Colors.white, fontSize: 18.0),),
                  IconButton(onPressed: () async {
                    await removeCoin( document.id );
                  }, icon: Icon( Icons.close, color: Colors.red, ), )
                  ], ), ),
              );
            }).toList(), );
          },), )
      ),
          floatingActionButton: FloatingActionButton(onPressed: () { 
            Navigator.push(context, MaterialPageRoute(builder: (context)=> AddView()));
          },
            child: Icon(Icons.add, color: Colors.white, ), backgroundColor: Colors.blueAccent,
          ),
    );
  }

  Future<void> getValues() async {

    bitcoin = (await getPrice('bitcoin'))!;
    ethereum = (await getPrice('ethereum'))!;
    tether = (await getPrice('tether'))!;
    setState(() {});
  }
}
 

Комментарии:

1. Не могли бы вы также предоставить JSON, который вы получаете в качестве ответа?