Flutter/Dart 空值检查: Text(“Price: ${getValue(document.id, document.data()['Amount'])}”), // data() 和 ['Amount'] 之间的红色下划线

Flutter/Dart null checking: Text("Price: ${getValue(document.id, document.data()['Amount'])}"), // red underline between data() and ['Amount']

提问人:Mark Zeiger 提问时间:9/26/2023 更新时间:9/26/2023 访问量:13

问:

我在 Flutter 中学习了一些在线教程,但 null 检查存在问题。我刚刚学习了 Flutter 和 Firebase 的优秀教程,但我有一种感觉,演示者正在使用 Flutter 的早期版本。我在指示的行中收到“空检查”错误

代码如下:


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crypto_wallet/net/api_methods.dart';
import 'package:crypto_wallet/ui/add_view.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class HomeView extends StatefulWidget {
  const HomeView({required Key key}) : super(key: key);

  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  double bitcoin = 0.0;
  double ethereum = 0.0;
  double tether = 0.0;

  @override
  initState() {
    super.initState();
    updateValues();
  }

  updateValues() async {
    bitcoin = await getPrice("bitcoin");
    ethereum = await getPrice("ethereum");
    tether = await getPrice("tether");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    getValue(String id, double amount) {
      if (id == "bitcoin") {
        return (bitcoin * amount).toStringAsFixed(2);
      } else if (id == "ethereum") {
        return (ethereum * amount).toStringAsFixed(2);
      } else {
        return (tether * amount).toStringAsFixed(2);
      }
    }

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        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 const Center(
                    child: CircularProgressIndicator(),
                  );
                }

                return ListView(
                  children: snapshot.data!.docs.map((document) {
                    return Container(
                        child: Row(
                      children: [
                        Text("Coin: ${document.id}"),
                        //***********
                        // Here's the problem
                        Text("Price: ${getValue(document.id, document.data()['Amount'])}"), 
                        // red underline between data() and ['Amount'] 


                      ],
                    ));
                  }).toList(),
                );
              }),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const AddView(),
            ),
          );
        },
        backgroundColor: Colors.blue,
        child: const Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
    );
  }
}**your text**

and the call to getPrice is:

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();
    return double.parse(value);
  } catch (e) {
    print(e.toString());
    return 0;
  }
}

我试过把?或!有问题的线路中的每个位置

飞镖

评论


答: 暂无答案