微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NoSuchMethodError: '[]' 从 Flutter 应用程序 api 重新调整 null 的动态调用

如何解决NoSuchMethodError: '[]' 从 Flutter 应用程序 api 重新调整 null 的动态调用

我试图调用这个 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);
  }
}

这是在 UI 上显示它的代码

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)}',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(() {});
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?