【问题标题】:Android Studio API CallAndroid Studio API 调用
【发布时间】:2022-01-17 23:04:18
【问题描述】:

我基本上可以按照本教程了解如何在 Flutter 中实现 API:https://docs.flutter.dev/cookbook/networking/fetch-data。我按照教程进行操作,但收到一条错误消息“类型'null 不是'String' 的子类型”。我已经尝试向标头添加其他参数,但这并没有解决问题。 我使用的 API 是汽车登记处,您可以在其中输入车牌并获取车辆的所有详细信息。

  final response = await http
      .get(Uri.parse('https://v1.motorapi.dk/vehicles/CZ33849'),
       headers: {"X-AUTH-TOKEN": "rfrzsucnc7eo3m5hcmq6ljdzda1lz793",
        "Content-Type": "application/json",
        "Accept": "application/json",
      });

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

//headers: {"X-AUTH-TOKEN": "rfrzsucnc7eo3m5hcmq6ljdzda1lz793"}

class Album {
  final String registration_number;
  final String status;
  final String type;
  final String use;
  final String first_registration;
  final String vin;
  final int doors;
  final String make;
  final String model;
  final String variant;
  final String model_type;
  final String color;
  final String chasis_type;
  final String engine_power;
  final String fuel_type;
  final String RegistreringssynToldsyn;
  final String date;
  final String result;

  Album({
    required this.registration_number,
    required this.status,
    required this.type,
    required this.use,
    required this.first_registration,
    required this.vin,
    required this.doors,
    required this.make,
    required this.model,
    required this.variant,
    required this.model_type,
    required this.color,
    required this.chasis_type,
    required this.engine_power,
    required this.fuel_type,
    required this.RegistreringssynToldsyn,
    required this.date,
    required this.result,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      registration_number: json['registration_number'],
      status: json['status'],
      type: json['type'],
      use: json['use'],
      first_registration: json['first_registration'],
      vin: json['vin'],
      doors: json['doors'],
      make: json['make'],
      model: json['model'],
      variant: json['variant'],
      model_type: json['model_type'],
      color: json['color'],
      chasis_type: json['chasis_type'],
      engine_power: json['engine_power'],
      fuel_type: json['fuel_type'],
      RegistreringssynToldsyn: json['RegistreringssynToldsyn'],
      date: json['date'],
      result: json['result'],
    );
  }
}

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!.registration_number);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

以及来自 API 的 Json 响应(我在 python 中测试了 API):

{'registration_number': 'CZ33849', 'status': 'Registreret', 'status_date': '2021-03-18T10:53:23.000+01:00', 'type': 'Personbil', 'use': 'Privat personkørsel', 'first_registration': '2020-03-17+01:00', 'vin': 'WVWZZZAWZLY087322', 'own_weight': None, 'total_weight': 1650, 'axels': 2, 'pulling_axels': 1, 'seats': 5, 'coupling': False, 'trailer_maxweight_nobrakes': 590, 'trailer_maxweight_withbrakes': 1000, 'doors': 4, 'make': 'VOLKSWAGEN', 'model': 'POLO', 'variant': '1,0', 'model_type': 'AW', 'model_year': 0, 'color': None, 'chassis_type': 'Hatchback', 'engine_cylinders': 3, 'engine_volume': 999, 'engine_power': 70, 'fuel_type': 'Benzin', 'registration_zipcode': '', 'vehicle_id': 9000000003974700, 'mot_info': {'type': 'RegistreringssynToldsyn', 'date': '2021-03-16', 'result': 'Godkendt', 'status': 'Aktiv', 'status_date': '2021-03-16'}}

【问题讨论】:

  • 我认为编译时会产生这个错误---{'color': None , 'own_weight': None } ---in your json.

标签: flutter android-studio


【解决方案1】:

您已将Album 类中的所有fields 标记为required,只需将它们设为nullable,这样API 就会返回一些null,然后class 也可以处理。 对您的班级进行以下更改

class Album {
  final String? registration_number;
  final String? status;
  final String? type;
  final String? use;
  final String? first_registration;
  final String? vin;
  final int? doors;
  final String? make;
  final String? model;
  final String? variant;
  final String? model_type;
  final String? color;
  final String? chasis_type;
  final String? engine_power;
  final String? fuel_type;
  final String? RegistreringssynToldsyn;
  final String? date;
  final String? result;

  Album({
    this.registration_number,
    this.status,
    this.type,
    this.use,
    this.first_registration,
    this.vin,
    this.doors,
    this.make,
    this.model,
    this.variant,
    this.model_type,
    this.color,
    this.chasis_type,
    this.engine_power,
    this.fuel_type,
    this.RegistreringssynToldsyn,
    this.date,
    this.result,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      registration_number: json['registration_number'],
      status: json['status'],
      type: json['type'],
      use: json['use'],
      first_registration: json['first_registration'],
      vin: json['vin'],
      doors: json['doors'],
      make: json['make'],
      model: json['model'],
      variant: json['variant'],
      model_type: json['model_type'],
      color: json['color'],
      chasis_type: json['chasis_type'],
      engine_power: json['engine_power'],
      fuel_type: json['fuel_type'],
      RegistreringssynToldsyn: json['RegistreringssynToldsyn'],
      date: json['date'],
      result: json['result'],
    );
  }
}

【讨论】:

  • 我已经进行了更改,但在这一行出现错误:return Text(snapshot.data!.registration_number); 错误是:参数类型“字符串?”不能分配给参数类型“字符串”。
  • 作为@Diwhansh 的回答,请记住,只要使用 Dart 2.12 或更高版本,null-safe 包可由尚未使用 null 安全性的包和应用程序使用
  • @WaiHanKo 请检查 MyApp 中的 Key 是否定义为可为空,这意味着该项目已经处于空安全状态。
  • @mhmh 只需使用 .toString() 方法 Text(snapshot.data!.registration_number.toString()) 转换为字符串,或者您可以将其作为 Text("${snapshot.data!.注册号}")
  • @Diwyansh 我已经进行了更改,但现在我收到一条错误消息:type 'int' is not a subtype of type 'String?'
猜你喜欢
  • 2022-01-13
  • 2021-12-27
  • 2020-05-24
  • 2013-05-11
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
相关资源
最近更新 更多