Невозможно получить идентификатор, получая данные из API - PullRequest
0 голосов
/ 02 ноября 2019

У меня проблема с извлечением данных в мое приложение из API

. Вот как выглядит идентификатор в базе данных:

 "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

1 Ответ

1 голос
/ 02 ноября 2019

Json.decode возвращает строку карты, динамическую, поэтому просто преобразуйте ваш carid в int при назначении.

id = int.parse (carid);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...