空检查运算符用于解决 flutter 中的空值问题

发布于 2025-01-11 13:28:03 字数 2749 浏览 1 评论 0原文

我遇到了 _CastError 的问题(在 null 值上使用 Null 检查运算符,当我在骑手应用程序中选择汽车服务和乘坐的最大要求时,它发生在 Flutter 项目中包含的 openstreet 地图中。

检查代码:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:ridy/generated/l10n.dart';
import '../graphql/generated/graphql_api.dart';
import 'bloc/main_bloc.dart';
import '../main/select_service_view.dart';
import 'package:velocity_x/velocity_x.dart';

class ServiceSelectionCardView extends StatelessWidget {
  const ServiceSelectionCardView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final mainBloc = context.read<MainBloc>();
    return BlocBuilder<MainBloc, MainBlocState>(builder: (context, state) {
      return Mutation(
        options: MutationOptions(document: CREATE_ORDER_MUTATION_DOCUMENT),
        builder: (RunMutation runMutation, QueryResult? result) {
          return Column(
            children: [
              FloatingActionButton.extended(
                      heroTag: 'cancelFab',
                      onPressed: () => mainBloc.add(ResetState()),
                      label: Text(S.of(context).action_cancel),
                      icon: const Icon(Icons.close))
                  .pOnly(bottom: 8)
                  .objectCenterRight(),
              SelectServiceView(
                data: (state as OrderPreview).fareResult,
                onServiceSelect: (String serviceId, int intervalMinutes) async {
                  final args = CreateOrderArguments(
                          input: CreateOrderInput(
                              serviceId: int.parse(serviceId),
                              intervalMinutes: 0,
                              points: state.points
                                  .map((e) => PointInput(
                                      lat: e.point.latitude,
                                      lng: e.point.longitude))
                                  .toList(),
                              addresses:
                                  state.points.map((e) => e.address).toList()))
                      .toJson();
                  final result = await runMutation(args).networkResult;
                  //print(result!.data!.toString());
                  final _order =
                      CreateOrder$Mutation.fromJson(result!.data!).createOrder;
                  mainBloc.add(OrderUpdated(order: _order));
                },
              ),
            ],
          );
        },
      );
    });
  }
}

请参阅此屏幕截图: 输入图片此处描述

I have the issue of _CastError (Null check operator used on a null value, its happened in openstreet map included in Flutter project when i choose service of car in rider app and greate reuest of ride.

check the code :

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:ridy/generated/l10n.dart';
import '../graphql/generated/graphql_api.dart';
import 'bloc/main_bloc.dart';
import '../main/select_service_view.dart';
import 'package:velocity_x/velocity_x.dart';

class ServiceSelectionCardView extends StatelessWidget {
  const ServiceSelectionCardView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final mainBloc = context.read<MainBloc>();
    return BlocBuilder<MainBloc, MainBlocState>(builder: (context, state) {
      return Mutation(
        options: MutationOptions(document: CREATE_ORDER_MUTATION_DOCUMENT),
        builder: (RunMutation runMutation, QueryResult? result) {
          return Column(
            children: [
              FloatingActionButton.extended(
                      heroTag: 'cancelFab',
                      onPressed: () => mainBloc.add(ResetState()),
                      label: Text(S.of(context).action_cancel),
                      icon: const Icon(Icons.close))
                  .pOnly(bottom: 8)
                  .objectCenterRight(),
              SelectServiceView(
                data: (state as OrderPreview).fareResult,
                onServiceSelect: (String serviceId, int intervalMinutes) async {
                  final args = CreateOrderArguments(
                          input: CreateOrderInput(
                              serviceId: int.parse(serviceId),
                              intervalMinutes: 0,
                              points: state.points
                                  .map((e) => PointInput(
                                      lat: e.point.latitude,
                                      lng: e.point.longitude))
                                  .toList(),
                              addresses:
                                  state.points.map((e) => e.address).toList()))
                      .toJson();
                  final result = await runMutation(args).networkResult;
                  //print(result!.data!.toString());
                  final _order =
                      CreateOrder$Mutation.fromJson(result!.data!).createOrder;
                  mainBloc.add(OrderUpdated(order: _order));
                },
              ),
            ],
          );
        },
      );
    });
  }
}

see this screenshot :
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

×眷恋的温暖 2025-01-18 13:28:03

当您 100% 确定变量不能为 null 时,请尝试使用 bang 运算符 !。看起来 result.data 实际上可以是 null,如果您记录结果,您会发现情况确实如此。您可以在序列化响应之前尝试先进行 null 检查:

if (result!=null){
 if (result!.data!=null){
  // result.data here is never `null`
 }
}

Try using the bang operator !, when you're 100% sure that the variable can't be null. Seems like result.data can in fact be null, if you log the result you will see that this is the case. You can try making a null check first before serializing the response :

if (result!=null){
 if (result!.data!=null){
  // result.data here is never `null`
 }
}
ペ泪落弦音 2025-01-18 13:28:03

将这一行更改

 CreateOrder$Mutation.fromJson(result!.data!).createOrder;

为这一行

 CreateOrder$Mutation.fromJson(result.data).createOrder;

Change this line

 CreateOrder$Mutation.fromJson(result!.data!).createOrder;

with this one

 CreateOrder$Mutation.fromJson(result.data).createOrder;
偷得浮生 2025-01-18 13:28:03

请尝试以下操作,希望对您有所帮助。您已将多余的 ! null 运算符删除。参考Flutter Sound null safety
此处此处

替换

result!.data!

为此

result!.data

完整声明:

final _order = CreateOrder$Mutation.fromJson(result!.data).createOrder;
                  mainBloc.add(OrderUpdated(order: _order));

Try below hope its help to you.you have put extra ! null operator remove it. Refer Flutter Sound null safety
here and here

Replace

result!.data!

to this

result!.data

Full declaration:

final _order = CreateOrder$Mutation.fromJson(result!.data).createOrder;
                  mainBloc.add(OrderUpdated(order: _order));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文