Home > OS >  type: 'Daftarangkot' is not a subtype of type 'DetailAngkot' in type cast
type: 'Daftarangkot' is not a subtype of type 'DetailAngkot' in type cast

Time:03-19

i am trying to make a list page get from api then want to show the details on the next page. I have followed the tutorial from the following link https://docs.flutter.dev/cookbook/navigation/passing-data when I click the detail page or the second page an error message appears "type: 'Daftarangkot' is not a subtype of type 'DetailAngkot' in type cast" on my emulator.

Below is first screen code.

import 'dart:ui';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kiriapp/angkottab/daftar.dart';
import 'package:kiriapp/angkottab/detailangkot.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

Future<List<Daftarangkot>> fetchData() async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  String? accessToken = sharedPreferences.getString("token");
  String? idOwner = sharedPreferences.getString("id");
  final response = await http.get(
    Uri.parse(
        "/api/angkot/find?owner_id=$idOwner"),
    headers: {
      'Authorization': 'Bearer $accessToken',
    },
  );
  print(response.statusCode);
  print(response.body);
  if (response.statusCode == 200) {
    Map<String, dynamic> map = json.decode(response.body);
    List<dynamic> jsonResponse = map["data"];
    return jsonResponse.map((data) => new Daftarangkot.fromJson(data)).toList();
  } else {
    throw Exception('Eror Ketika Menampilkan! Diharap Login Ulang.');
  }
}

class Daftarangkot {
  final String id;
  final String plat_nomor;
  final String status;
  final String pajak_tahunan;

  Daftarangkot(
      {required this.id,
      required this.plat_nomor,
      required this.status,
      required this.pajak_tahunan});

  factory Daftarangkot.fromJson(Map<String, dynamic> json) {
    return Daftarangkot(
      id: json['plat_nomor'],
      plat_nomor: json['plat_nomor'],
      status: json['status'],
      pajak_tahunan: json['pajak_tahunan'],
    );
  }
}

class DetailAngkot {
  final String detail_id;
  final String detail_plat_nomor;
  final String detail_pajak_tahunan;
  final String detail_pajak_stnk;
  final String detail_kir_bulanan;
  final String detail_is_beroperasi;
  final String detail_status;

  const DetailAngkot(
    this.detail_id,
    this.detail_plat_nomor,
    this.detail_pajak_tahunan,
    this.detail_pajak_stnk,
    this.detail_kir_bulanan,
    this.detail_is_beroperasi,
    this.detail_status,
  );
}

class AngkotsScreen extends StatefulWidget {
  const AngkotsScreen({Key? key, required this.angkots}) : super(key: key);

  final List<DetailAngkot> angkots;
  @override
  State<AngkotsScreen> createState() => _AngkotsScreenState();
}

class _AngkotsScreenState extends State<AngkotsScreen> {
  late Future<List<Daftarangkot>> futureData;

  @override
  void initState() {
    super.initState();
    futureData = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(right: 16, left: 16, top: 14),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FutureBuilder<List<Daftarangkot>>(
                future: futureData,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<Daftarangkot>? data = snapshot.data;
                    return ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        itemCount: data?.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Column(
                            children: [
                              Card(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(15.0),
                                ),
                                elevation: 8,
                                child: new InkWell(
                                  onTap: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => Detailangkot(),
                                          settings: RouteSettings(
                                            arguments: data![index],
                                          ),
                                        ));
                                  },
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        left: 14, top: 12, bottom: 12),
                                    child: Row(
                                      children: [
                                        Image.asset('assets/img/mobil.png'),
                                        Padding(
                                          padding: const EdgeInsets.only(
                                              left: 14, right: 16),
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              Text(data![index].plat_nomor,
                                                  style: TextStyle(
                                                      fontFamily: 'PoppinsBold',
                                                      fontSize: 24)),
                                              Text(data[index].status,
                                                  style: TextStyle(
                                                      fontFamily: 'PoppinsReg',
                                                      fontSize: 18,
                                                      color:
                                                          Color(0xFF3FC100))),
                                              Text(data[index].pajak_tahunan,
                                                  style: TextStyle(
                                                      fontFamily: 'PoppinsReg',
                                                      fontSize: 14)),
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(
                                height: 8,
                              ),
                            ],
                          );
                        });
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }
                  // By default show a loading spinner.
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                },
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => DaftarAngkot()));
        },
        backgroundColor: Color(0xff38AC00),
        child: const Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
    );
  }
}

and this is the code of the second page or the detail page

import 'dart:ui';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kiriapp/BarChartSample1.dart';
import 'package:kiriapp/angkot.dart';
import 'package:kiriapp/home.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class Detailangkot extends StatefulWidget {
  const Detailangkot({Key? key}) : super(key: key);
  @override
  State<Detailangkot> createState() => _DetailangkotState();
}

class _DetailangkotState extends State<Detailangkot> {
  @override
  Widget build(BuildContext context) {
    final angkot = ModalRoute.of(context)!.settings.arguments as DetailAngkot;
    // TODO: implement build
    return Scaffold(
      backgroundColor: Color(0xFFEFEFEF),
      appBar: AppBar(
        iconTheme: IconThemeData(
          color: Colors.white, //change your color here
        ),
        title: Text(
          "Detail Angkot",
          style: TextStyle(
              fontFamily: 'PoppinsReg', fontSize: 24, color: Colors.white),
        ),
        backgroundColor: Color(0xFF38AC00),
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 8,
              ),
              Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15.0),
                ),
                elevation: 8,
                child: Padding(
                  padding: const EdgeInsets.only(left: 14, top: 12, bottom: 12),
                  child: Row(
                    children: [
                      Image.asset('assets/img/mobil.png'),
                      Padding(
                        padding: const EdgeInsets.only(left: 14, right: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(angkot.detail_plat_nomor,
                                style: TextStyle(
                                    fontFamily: 'PoppinsBold', fontSize: 24)),
                            Text(angkot.detail_status,
                                style: TextStyle(
                                    fontFamily: 'PoppinsReg',
                                    fontSize: 18,
                                    color: Color(0xFF3FC100))),
                            Row(
                              children: [
                                Text('Sopir ',
                                    style: TextStyle(
                                        fontFamily: 'PoppinsReg',
                                        fontSize: 16,
                                        color: Color(0xFF727272))),
                                Text('Rizky',
                                    style: TextStyle(
                                        fontFamily: 'PoppinsSemBold',
                                        fontSize: 16,
                                        color: Colors.black)),
                              ],
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Thanks

CodePudding user response:

in here

Navigator.push(
     context,
     MaterialPageRoute(
     builder: (context) => Detailangkot(),
     settings: RouteSettings(
         arguments: data![index],
     ),
 ));

you are sending a Daftarangkot object

while here

    final angkot = ModalRoute.of(context)!.settings.arguments as DetailAngkot;

you are expecting it as DetailAngkot. thus it throws this error.

  • Related