我怎样才能对这个进行空检查?

How can I null-check this?

FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) => Text(
    "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
    textAlign: TextAlign.center,
    style: TextStyle(fontSize: 20),
  ), // Text
), // FutureBuilder

我在 snapshot.data 中遇到“一个值为 'null' 的表达式必须在取消引用之前对其进行空检查。”错误。我怎样才能对此进行空检查?

GetLiter() 函数在这里 =>

Future<Object?> GetLiter() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");

  DatabaseEvent event = await ref.once();

  // print(event.snapshot.value);
  return event.snapshot.value;
} 

FutureBuilders 在构建之前不会等待未来完成,因此 snapshot.data 可能为空。您需要在构建之前检查它,否则构建将失败。试试这个:

import 'package:flutter/material.dart';


FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) {
    if(snapshot.hasError){
      print(snapshot.error);
    }
    if(snapshot.hasData){
      return Text(
        "Estimated bill \n\n\n" + snapshot.data! * 0.00556 + " $",
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 20),
      ),
    } else {
      return CircularProgressIndicator();
    }
  }
), 

您可以在 builder 上使用 snapshot.hasData 来检查它是否为空。例如:

FutureBuilder(
  future: GetLiter(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return Text('Nothing here');
    return Text(
      "Estimated bill \n\n\n" + snapshot.data * 0.00556 + " $",
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 20),
    )
  }, // Text
),

使用 FutureBuilder 时,您需要等待数据并处理加载状态和空数据。

child: FutureBuilder<Object?>(
  future: GetLiter(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    } else if (snapshot.hasData &&
        snapshot.connectionState == ConnectionState.done) {
      return Text("Got Data");
    } else if (!snapshot.hasData) {
      return Text("no Data");
    } else if (snapshot.hasError) {
      return Text(snapshot.error.toString());
    } else {
      return Text("others");
    }
  },
),

更多关于FutureBuilder