如何在构建器内解决变量的空检查运算符?

huangapple go评论72阅读模式
英文:

How to resolve null check operator of a variable within a builder?

问题

以下是您提供的代码的翻译部分:

我正在编写一个QR码扫描器的函数语句。当它没有面对QR码时,它应该在else if语句中处于等待状态

```dart
else if (result == null) {
  return Column(
   children: [ const Text("欢迎!"), Text("费用:${load["Fee"]}"), ],
  );
 } 

这里的问题是语句late Message data = Message.fromJson(jsonDecode((result!.code!)));如果没有FutureBuilder的话是正常工作的。但是加上它后,它会显示一个异常,指向一个奇怪的变量语句,该异常为“Null check operator used on a null value”。

如何解决这个问题?我想通过else if语句在等待状态下显示。

Barcode? result;
FutureBuilder<DocumentSnapshot>(
  future: FirebaseFirestore.instance
      .collection('Drivers')
      .doc(FirebaseAuth.instance.currentUser?.email)
      .get(),
  builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (snapshot.hasError) { return Text("出现了一些问题"); }
    if (snapshot.hasData && !snapshot.data!.exists) { return Text("文档不存在"); }
    if (snapshot.connectionState == ConnectionState.done) {
      Map<String, dynamic> load = snapshot.data!.data() as Map<String, dynamic>;

          late Message data = Message.fromJson(jsonDecode((result!.code!))); // 除非没有Builder,否则运行时会出现Null check Operator错误。
         int total = data.price * data.passenger;
      return Column(
        children: [
          Row(children: [Text(load["name"]),],),
          // <--- 这里有Builder
          Container(
            height: 100,
            child: Row(
              mainAxisAlignment:
                  MainAxisAlignment.spaceEvenly,
              children: [
                // FutureBuilder<DocumentSnapshot>(), 需要访问乘客列表。&&(load["Fee"] == data.price)
                Container(child: LayoutBuilder(builder: (context, constraints) {
                  if ((result != null) && (load["Fee"] == data.price)) {
                    return FutureBuilder<DocumentSnapshot>(
                      future: FirebaseFirestore.instance.collection('Users').doc(data.email).get(),
                      builder:(context, snapshot) {
                        if ((snapshot.hasError)||(snapshot.hasData && !snapshot.data!.exists)) { return const Text("出了些问题,请重试"); }
                        if (snapshot.connectionState == ConnectionState.done) {
                          Map<String, dynamic> moneycheck = snapshot.data!.data() as Map<String, dynamic>;

                          if (moneycheck['Balance'] >= total){
                            //addPayRowUser(data.email, data.totalprice);
                            return Column(
                              children: [
                                Text("付款成功! \n ${DateTime.now().toString()}"),
                                Text("价格: RM${data.price} 每人"),
                                Text("总计: RM${data.totalprice}"),
                                Text("人数: ${data.passenger}"),
                              ],
                            );
                          }
                          else if (moneycheck['Balance'] < total){ return 
                          Column( children: [ Text("余额不足"),
                                Text("余额: RM ${moneycheck['Balance']}"),Text("价格: RM${data.price} 每人"),
                                 Text("总计: RM${data.totalprice}"),Text("人数: ${data.passenger}"),
                              ],
                            );
                           }
                        }
                        return const Text("加载中...");
                      },
                    );
                  } 
                  else if (result == null) {
                    return Column(
                      children: [ const Text("欢迎!"), Text("费用:${load["Fee"]}"), ],
                    );
                  } 
                  else if ((result != null) && (load["Fee"] != data.price)) 
                  {
                    return Column(
                      children: [ const Text("无效的QR码!"), Text("${data.price}"), Text("${data.totalprice}"),],
                    );
                  } 
                  else {
                    return const Column(
                      children: [
                        Text("发生未知错误"),
                      ],
                    );
                  }
                })
                    // Text('Payment Made! \nPickup: ${data.pickup} \nDropoff: ${data.dropoff} \n Price:${data.balance}');
                    )
              ],
            ),
          ),
        ],
      );
    }
    return const Text("加载中");
  },
)

希望这有助于您理解代码。如果您需要任何进一步的帮助,请随时告诉我。

英文:

I'm doing a function statement of QR Code Scanner. When it's not facing the QR Code, it should be in waiting state in else if statement.

else if (result == null) {
return Column(
children: [ const Text(&quot;Welcome!&quot;), Text(&quot;Fee:${load[&quot;Fee&quot;]}&quot;), ],
);
} 

The problem here is the statement late Message data = Message.fromJson(jsonDecode((result!.code!))); works well if there is no FutureBuilder. But with that, it shows an Exception, Null check operator used on a null value, pointing at the statement of a variable strangely enough.

How can I resolve that? I want to display in waiting state by an else if statement.

Barcode? result;
FutureBuilder&lt;DocumentSnapshot&gt;(
future: FirebaseFirestore.instance
.collection(&#39;Drivers&#39;)
.doc(FirebaseAuth.instance.currentUser?.email)
.get(),
builder: (BuildContext context, AsyncSnapshot&lt;DocumentSnapshot&gt; snapshot) {
if (snapshot.hasError) { return Text(&quot;Something went wrong&quot;); }
if (snapshot.hasData &amp;&amp; !snapshot.data!.exists) { return Text(&quot;Document does not exist&quot;); }
if (snapshot.connectionState == ConnectionState.done) {
Map&lt;String, dynamic&gt; load = snapshot.data!.data() as Map&lt;String, dynamic&gt;;
late Message data = Message.fromJson(jsonDecode((result!.code!))); //Null check Operator Runtime Error unless no Builder there.
int total = data.price * data.passenger;
return Column(
children: [
Row(children: [Text(load[&quot;name&quot;]),],),
//&lt;--- Builder Here
Container(
height: 100,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
//FutureBuilder&lt;DocumentSnapshot&gt;(), Needs to access Passenger List. &amp;&amp;(load[&quot;Fee&quot;] == data.price)
Container(child: LayoutBuilder(builder: (context, constraints) {
if ((result != null) &amp;&amp; (load[&quot;Fee&quot;] == data.price)) {
return FutureBuilder&lt;DocumentSnapshot&gt;(
future: FirebaseFirestore.instance.collection(&#39;Users&#39;).doc(data.email).get(),
builder:(context, snapshot) {
if ((snapshot.hasError)||(snapshot.hasData &amp;&amp; !snapshot.data!.exists)) { return const Text(&quot;Something went wrong, Try again&quot;); }
if (snapshot.connectionState == ConnectionState.done) {
Map&lt;String, dynamic&gt; moneycheck = snapshot.data!.data() as Map&lt;String, dynamic&gt;;
if (moneycheck[&#39;Balance&#39;] &gt;= total){
//addPayRowUser(data.email, data.totalprice);
return Column(
children: [
Text(&quot;Payment Made! \n ${DateTime.now().toString()}&quot;),
Text(&quot;Price: RM${data.price} per Person&quot;),
Text(&quot;Total: RM${data.totalprice}&quot;),
Text(&quot;Persons: ${data.passenger}&quot;),
],
);
}
else if (moneycheck[&#39;Balance&#39;] &lt; total){ return 
Column( children: [ Text(&quot;Insufficient Balance&quot;),
Text(&quot;Balance: RM ${moneycheck[&#39;Balance&#39;]}&quot;),Text(&quot;Price: RM${data.price} per Person&quot;),
Text(&quot;Total: RM${data.totalprice}&quot;),Text(&quot;Persons: ${data.passenger}&quot;),
],
);
}
}
return const Text(&quot;Loading...&quot;);
},
);
} 
else if (result == null) {
return Column(
children: [ const Text(&quot;Welcome!&quot;), Text(&quot;Fee:${load[&quot;Fee&quot;]}&quot;), ],
);
} 
else if ((result != null) &amp;&amp; (load[&quot;Fee&quot;] != data.price)) 
{
return Column(
children: [ const Text(&quot;Invalid QR Code!&quot;), Text(&quot;${data.price}&quot;), Text(&quot;${data.totalprice}&quot;),],
);
} 
else {
return const Column(
children: [
Text(&quot;Unknown Error Occured&quot;),
],
);
}
})
//Text(&#39;Payment Made! \nPickup: ${data.pickup} \nDropoff: ${data.dropoff} \n Price:${data.balance}&#39;),
)
],
),
),
],
);
}
return const Text(&quot;Loading&quot;);
},
)

答案1

得分: 0

String? qrcode = result?.code??&quot;&quot;;
late Message data = Message.fromJson(jsonDecode((qrcode??&quot;&quot;)));
英文:

Solution:

String? qrcode = result?.code??&quot;&quot;;
late Message data = Message.fromJson(jsonDecode((qrcode??&quot;&quot;)));

huangapple
  • 本文由 发表于 2023年6月1日 01:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定