简体   繁体   English

我在 dart - flutter 应用程序中遇到空检查问题

[英]i have a problem with null-checking in dart - flutter app

the problem is that I have two cars when I fetch the data with getting request the existing cars that work give me the information that I need but when I access the car that has null information the flutter gives me an error this is my code问题是我有两辆车,当我通过获取请求获取数据时,现有的可用汽车为我提供了我需要的信息,但是当我访问具有 null 信息的汽车时,flutter 给了我一个错误,这是我的代码

class Vehicle {
  Vehicle({
    @required this.id,
    @required this.name,
    @required this.status,
    @required this.position,
    @required this.vehicleId,
    @required this.driver,
    @required this.motionState,
    @required this.motionTime,
    @required this.immobileFeature,
    @required this.geofenceIds,
    @required this.deviceState,
  });

  final int? id;
  final String? name;
  final String? status;
  final Position? position;
  final int? vehicleId;
  final Driver? driver;
  final String? motionState;
  final String? motionTime;
  final bool? immobileFeature;
  final List<dynamic>? geofenceIds;
  final DeviceState? deviceState;

  factory Vehicle.fromJson(Map<String, dynamic> json) => Vehicle(
        id: json["id"],
        name: json["name"],
        status: json["status"],
        position: json["position"] == null
            ? null
            : Position.fromJson(json["position"]),
        vehicleId: json["vehicleId"],
        driver: json["driver"] == null ? null : Driver.fromJson(json["driver"]),
        motionState: json["motionState"],
        motionTime: json["motionTime"] == null ? null : json["motionTime"],
        immobileFeature: json["immobileFeature"],
        geofenceIds: json["geofenceIds"] == null
            ? null
            : List<dynamic>.from(json["geofenceIds"].map((x) => x)),
        deviceState: json["deviceState"] == null
            ? null
            : DeviceState.fromJson(json["deviceState"]),
      );
}

**this is the main file I don't know if i need to put a variable for each null item or where the problem is ** **这是主文件我不知道我是否需要为每个 null 项目或问题所在放置一个变量**

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<List<Vehicle>> futureVehicle;

  @override
  void initState() {
    super.initState();
    futureVehicle = fetchVehicle();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ),
      home: Scaffold(
        ),
        body: FutureBuilder<List<Vehicle>>(
          future: futureVehicle,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return (ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (_, index) => GestureDetector(
                  onTap: () => Navigator.of(context).push(
                    MaterialPageRoute(
                      fullscreenDialog: true,
                      // ignore: prefer_const_constructors
                      builder: (context) => carscreen(snapshot.data[index]),
                    ),
                  ), 
                     children: [
                        Text(
                          "${snapshot.data[index].name}",
                          style: TextStyle(
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 10),
                        Text("${snapshot.data[index].id}"),
                        SizedBox(height: 10),
                        Text("${snapshot.data[index].name}"),
                        SizedBox(height: 10),
                        Text("${snapshot.data[index].vehicleId}"),
                        SizedBox(height: 10),
                        Text("${snapshot.data[index].motionState}"),
                      ],
                    ),
                  ),
                ),
              ));
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}
factory Vehicle.fromJson(Map<String, dynamic> json) => Vehicle(
        id: json["id"],
        name: json["name"],
        status: json["status"],
        position: json["position"] == null
            ? new Position(
                fixTime: '',
                speed: 0,
                bearing: 0,
                address: 'null',
                latlng: [],
                attributes: new Attributes(
                    alarm: '',
                    immobile: '',
                    odometer: 0,
                    fuelUsed: 0,
                    avgFuelUsed: 0,
                    ignition: false,
                    coolantTemp: 0,
                    power: 0,
                    battery: 0))
            : Position.fromJson(json["position"]),
        vehicleId: json["vehicleId"],
        driver: json["driver"] == null
            ? new Driver(name: 'null', phone: 'null')
            : Driver.fromJson(json["driver"]),
        motionState: json["motionState"],
        motionTime: json["motionTime"] == null ? null : json["motionTime"],
        immobileFeature: json["immobileFeature"],
        geofenceIds: json["geofenceIds"] == null
            ? null
            : List<dynamic>.from(json["geofenceIds"].map((x) => x)),
        deviceState: json["deviceState"] == null
            ? new DeviceState(parkingAddress:  'null', tracks:  [], traveldistance: 0, travelingDuration: 00)
            : DeviceState.fromJson(json["deviceState"]),
      );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM