无法通过从API提取数据来获取ID

问题描述 投票:0回答:1

从API将数据提取到我的应用程序时遇到问题

这是ID在数据库中的外观:

 "id": 127,

这是我的提取代码的外观:

Future<void> fetchAndSetCars() async {
    const url =
        "my API link";
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<int, dynamic>;
      List<AddCar> loadedCars = [];

      extractedData.forEach((carId, carData) {
        loadedCars.add(AddCar(
          id: carId,
          name: carData['adTitle'],
          price: carData['AdPrice'],
          date: carData['adDate'],
          model: carData['brandModel'],
          year: carData['modelYear'],
          distanceCovered: carData['kilometer'],
          transmission: carData['gearType'],
          oilT: carData['fuelType'],
          image: File(carData['image']),
        ));
      });
      _cars = loadedCars;
      print(json.decode(response.body));
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

这是我的提供者代码:

import 'dart:io';

class AddCar {
  int id;
  String name;
  double price;
  String date;
  String model;
  String year;
  double distanceCovered;
  String transmission;
  String oilT;
  File image;

  AddCar({
    this.id,
    this.name,
    this.price,
    this.date,
    this.model,
    this.year,
    this.distanceCovered,
    this.transmission,
    this.oilT,
    this.image,
  });
}

这是我的CarItem“显示数据的位置”:

class CarItem extends StatelessWidget {
  final int id;
  final File image;
  final String name;
  final String model;
  final String currencyT;
  final double price;
  final double distanceCovered;
  final String transmission;
  final String oilT;
  final String year;
  final String date;

  CarItem(
    this.id,
    this.image,
    this.name,
    this.model,
    this.currencyT,
    this.price,
    this.distanceCovered,
    this.transmission,
    this.oilT,
    this.year,
    this.date,
  );

  @override
  Widget build(BuildContext context) {
    return Container(),

这是我的ListView.builder和我的提取代码:

@override
  void didChangeDependencies() {
    if (_isInit) {
      setState(() {
        _isLoading = true;
      });
      Provider.of<Cars>(context).fetchAndSetCars().then((_) {
        setState(() {
          _isLoading = false;
        });
      });
    }
    _isInit = false;
    super.didChangeDependencies();
  }

ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount: car.length = 1,
                    shrinkWrap: true,
                    itemBuilder: (ctx, i) => CarItem(
                      car[i].id,
                      car[i].image,
                      car[i].name,
                      car[i].model,
                      car[i].currencyT,
                      car[i].price,
                      car[i].distanceCovered,
                      car[i].transmission,
                      car[i].oilT,
                      car[i].year,
                      car[i].date,
                    ),
                  )

这是运行时错误:

I/flutter (  968): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (  968): The following NoSuchMethodError was thrown building:
I/flutter (  968): The getter 'id' was called on null.
I/flutter (  968): Receiver: null
I/flutter (  968): Tried calling: id

还有另一个错误:

E/flutter (  968): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<int, dynamic>' in type cast
E/flutter (  968): #0      Cars.fetchAndSetCars 
package:flutter_app/providers/car_provider.dart:61
E/flutter (  968): <asynchronous suspension>
E/flutter (  968): #1      _CarAreaState.didChangeDependencies
flutter error-handling fetch-api
1个回答
1
投票

Json.decode返回动态的Map字符串,因此只需将您的carid转换为int即可。

id = int.parse(carid);

© www.soinside.com 2019 - 2024. All rights reserved.