Ad

ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Type 'String' Is Not A Subtype Of Type 'int' In Type Cast

- 1 answer

I'm trying to persist data within a SQFlite Database! The error occurs for the value 'kilometer'. It was supposed to be int until i got this error. Then I tried changing the value to String. After that I got the opposite error which said 'int is not a subtype of String'. Actually I have no idea what is wrong.

here's my code:

class MyCar:
'''

final String tableCar='car';

class CarFields{
  static final List<String> values=[
    id,marke,modell,baujahr, motor,hubraum, kilometer
  ];


  static final String id='_id';
  static final String marke='marke';
  static final String modell='modell';
  static final String baujahr='baujahr';
  static final String motor='motor';
  static final String hubraum='hubraum';
  static final String kilometer='kilometer';
}

class MyCar{
  final int? id;
  final String marke;
  final String modell;
  final String baujahr;
  final String motor;
  final String hubraum;
  final int kilometer;

  const MyCar({
    this.id,
    required this.marke,
    required this.modell,
    required this.baujahr,
    required this.motor,
    required this.hubraum,
    required this.kilometer,

});
  MyCar copy({
    int? id,
    String? marke,
    String? modell,
    String? baujahr,
    String? motor,
    String? hubraum,
    int? kilometer,

}) => MyCar(
    id: id?? this.id,
    marke: marke?? this.marke,
    modell: modell ?? this.modell,
    baujahr: baujahr ?? this.baujahr,
    motor: motor?? this.motor,
    hubraum: hubraum ?? this.hubraum,
    kilometer: kilometer ?? this.kilometer,
  );
static MyCar fromJson(Map<String, Object?> json)=> MyCar(
  id: json[CarFields.id] as int?,
  marke: json[CarFields.marke] as String,
  modell: json[CarFields.modell] as String,
  baujahr: json[CarFields.baujahr] as String,
  motor: json[CarFields.motor] as String,
  hubraum: json[CarFields.hubraum] as String,
  kilometer: json[CarFields.kilometer] as int,
);

  Map<String, Object?> toJson()=>{
    CarFields.id:id,
    CarFields.marke:marke,
    CarFields.modell:modell,
    CarFields.baujahr:baujahr,
    CarFields.motor:motor,
    CarFields.hubraum:hubraum,
    CarFields.kilometer:kilometer,

  };

}
'''

class CarFormWidget:
'''
import 'package:flutter/material.dart';

class CarFormWidget extends StatelessWidget{

  final String? marke;
  final String? modell;
  final String? baujahr;
  final String? motor;
  final String? hubraum;
  final int? kilometer;
  final ValueChanged<String> onChangedMarke;
  final ValueChanged<String> onChangedModell;

  const CarFormWidget({
    Key? key,
    this.marke='',
    this.modell='',
    this.baujahr='',
    this.motor='',
    this.hubraum='',
   this.kilometer=0,
    required this.onChangedMarke,
    required this.onChangedModell,
}): super(key:key);

  @override
  Widget build(BuildContext context) => SingleChildScrollView(
    child: Padding(
      padding: EdgeInsets.all(16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(


          ),
          buildMarke(),
          SizedBox(height: 8),
          buildModell(),
          SizedBox(height: 8),
          buildBaujahr(),
          SizedBox(height: 8),
          buildMotor(),
          SizedBox(height: 8),
          buildHubraum(),
          SizedBox(height: 8),
          buildKilometer(),
        ],
      ),
    ),
  );
  Widget buildMarke() => TextFormField(
    maxLines: 1,
    initialValue: marke,
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Marke',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (marke) =>
    marke != null && marke.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );


  Widget buildModell() => TextFormField(
    maxLines: 1,
    initialValue: modell,
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Modell',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (modell) =>
    modell != null && modell.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );

  Widget buildBaujahr() => TextFormField(
    maxLines: 1,
    initialValue: baujahr,
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Baujahr',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (baujahr) =>
    baujahr != null && baujahr.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );

  Widget buildMotor() => TextFormField(
    maxLines: 1,
    initialValue: motor,
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Motor',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (motor) =>
    motor != null && motor.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );

  Widget buildHubraum() => TextFormField(
    maxLines: 1,
    initialValue: hubraum,
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Hubraum',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (hubraum) =>
    hubraum != null && hubraum.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );
  Widget buildKilometer() => TextFormField(
    maxLines: 1,
    initialValue: 'Kilometer',
    style: TextStyle(
      color: Colors.white70,
      fontWeight: FontWeight.bold,
      fontSize: 24,
    ),
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: 'Kilometer',
      hintStyle: TextStyle(color: Colors.white70),
    ),
    validator: (kilometer) =>
    kilometer != null && kilometer.isEmpty ? 'The Marke cannot be empty' : null,
    onChanged: onChangedMarke,
  );
}

'''
class CarDatabase:

'''
import 'package:path/path.dart';
import 'package:recarable/classes/MyCar.dart';
import 'package:sqflite/sqflite.dart';

class CarDatabase {
  static final CarDatabase instance = CarDatabase._init();

  static Database? _database;

  CarDatabase._init();

  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await _initDB('MyCars.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    final idType = 'INTEGER PRIMARY KEY AUTOINCREMENT';
    final textType = 'TEXT NOT NULL';
    final integerType = 'INTEGER NOT NULL';



    await db.execute('''
CREATE TABLE $tableCar ( 
  ${CarFields.id} $idType,
  ${CarFields.marke} $textType,
  ${CarFields.modell} $textType,
  ${CarFields.baujahr} $textType,
  ${CarFields.motor} $textType,
  ${CarFields.hubraum} $textType,
  ${CarFields.kilometer} $textType
  )
''');
  }
//


  Future<MyCar> create(MyCar mycar) async {
    final db = await instance.database;

    final id = await db.insert(tableCar, mycar.toJson());


    return mycar.copy(id: id);
  }

  Future<MyCar> readNote(int id) async {
    final db = await instance.database;

    final maps = await db.query(
      tableCar,
      columns: CarFields.values,
      where: '${CarFields.id}=?',
      whereArgs: [id],
    );
    if (maps.isNotEmpty) {
      return MyCar.fromJson(maps.first);
    } else {
      throw Exception('ID $id not found');
    }
  }

  Future<List<MyCar>> readAllMyCars() async {
    final db = await instance.database;
    final orderBy = '${CarFields.id} ASC';
    final result = await db.query(tableCar, orderBy: orderBy);
    return result.map((json) => MyCar.fromJson(json)).toList();
  }

  Future<int> update(MyCar mycar) async {
    final db = await instance.database;
    return db.update(
      tableCar,
      mycar.toJson(),
      where: '${CarFields.id}=?',
      whereArgs: [mycar.id],
    );
  }

  Future<int> delete(int id) async {
    final db = await instance.database;

    return await db.delete(
      tableCar,
      where: '${CarFields.id}=?',
      whereArgs: [id],
    );
  }

  Future close() async {
    final db = await instance.database;

    db.close();
  }
}

'''
Ad

Answer

Maybe the response you are getting is inconsistent. Some datas are int, some are string. So the best way to not get this error is to use dynamic.

Just use dynamic kilometer in your MyCar class. Also, remove as int

MyCar copy({
    int? id,
    String? marke,
    String? modell,
    String? baujahr,
    String? motor,
    String? hubraum,
    dynamic kilometer,

}) => MyCar(
    id: id?? this.id,
    marke: marke?? this.marke,
    modell: modell ?? this.modell,
    baujahr: baujahr ?? this.baujahr,
    motor: motor?? this.motor,
    hubraum: hubraum ?? this.hubraum,
    kilometer: kilometer ?? this.kilometer,
  );
static MyCar fromJson(Map<String, Object?> json)=> MyCar(
  id: json[CarFields.id] as int?,
  marke: json[CarFields.marke] as String,
  modell: json[CarFields.modell] as String,
  baujahr: json[CarFields.baujahr] as String,
  motor: json[CarFields.motor] as String,
  hubraum: json[CarFields.hubraum] as String,
  kilometer: json[CarFields.kilometer],
);
Ad
source: stackoverflow.com
Ad