Home > Software design >  Flutter 'List<dynamic>' is not a subtype of type 'List<Widget>'
Flutter 'List<dynamic>' is not a subtype of type 'List<Widget>'

Time:09-17

I receive this exception as thrown in the line ShowChart(data: dataapi.data) although i define it as a list below. I also tried to map my List data but no solution. I am new to flutter, sorry if this is a dummy question.

The exception thrown :

════════ Exception caught by widgets library ═══════════════════════════════════
type 'List<Series<Hakedis, dynamic>>' is not a subtype of type 'List<Series<dynamic, num>>'
The relevant error-causing widget was
ShowChart
lib/screens/pageThree.dart:49
════════════════════════════════════════════════════════════════════════════════

The code:

// MAIN WIDGET

class PageThree extends StatefulWidget {
  final String url;

  const PageThree({this.url});

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

class _PageThreeState extends State<PageThree> {
  var chart;

  Future<List<Hakedis>> getChartData(widget) async {
    final jsonEndpoint = "https://securityconcern.php";
    final response = await get(jsonEndpoint);
    final List<dynamic> jsonData = jsonDecode(response.body);
    return jsonData.map((data) => Hakedis.fromJson(data)).toList();
  }


  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('GraphTest'),
        ),
        body: Padding(
          padding: EdgeInsets.all(8.0),
          child: FutureBuilder<List>(
            future: getChartData(widget),
            builder: (context, dataapi) {
              if (dataapi.hasError) print(dataapi.error);
              return dataapi.hasData
                  ? ShowChart(data: dataapi.data)
                  : Center(child: CircularProgressIndicator());
            },
          ),
        ),
      ),
    );
  }
}


// CHART

class ShowChart extends StatelessWidget {
  final List<Hakedis> data;
  
  ShowChart({this.data});

  static List<charts.Series<Hakedis, dynamic>> _createSampleData(dataAPI) {
    return [
      new charts.Series<Hakedis, dynamic>(
        id: 'dis adet',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        areaColorFn: (_, __) =>
            charts.MaterialPalette.blue.shadeDefault.lighter,
        //x-axis
        domainFn: (Hakedis hakedis, _) => hakedis.tarih,
        //y-axis
        measureFn: (Hakedis hakedis, _) => double.tryParse(hakedis.disadet).round(),
        data: dataAPI,
      )
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: charts.LineChart(
        _createSampleData(data),
        defaultRenderer:
            new charts.LineRendererConfig(includeArea: true, stacked: true),
        animate: true,
        domainAxis: charts.NumericAxisSpec(
          tickProviderSpec:
              charts.BasicNumericTickProviderSpec(zeroBound: false),
        ),
      ),
    );
  }
}


/////////////////////////////////////

class Hakedis {
  Hakedis({
    this.id,
    this.tarih,
    this.disadet,
  });
  
  final int id;
  String disadet;
  DateTime tarih;


  factory Hakedis.fromJson(Map<String, dynamic> jsonData) => Hakedis(
      id: jsonData['id'],
      tarih: jsonData['tarih'],
      disadet: jsonData['disadet'],
        );

    Map<String, dynamic> toJson() => {
          "id": id,
          "tarih": tarih,
          "disadet": disadet,
        };

}

The data i am parsing via API; (here is the "tarih" column gets month name as date, and i am trying to convert into datetime format)

[{"santiye1":"TSK_Ankara","tarih":"August","disadet":"1252"},{"santiye1":"TSK_Ankara","tarih":"September","disadet":"6528"},{"santiye1":"KMO_Istanbul","tarih":"August","disadet":"4382"},{"santiye1":"KMO_Istanbul","tarih":"September","disadet":"3317"},{"santiye1":"izmit","tarih":"January","disadet":"400"},{"santiye1":"izmit","tarih":"February","disadet":"7883"},{"santiye1":"izmit","tarih":"March","disadet":"9601"},{"santiye1":"izmit","tarih":"April","disadet":"25692"},{"santiye1":"izmit","tarih":"May","disadet":"15714"},{"santiye1":"izmit","tarih":"June","disadet":"28024"},{"santiye1":"izmit","tarih":"July","disadet":"18179"},{"santiye1":"izmit","tarih":"December","disadet":"3612"},{"santiye1":"Akkuyu1","tarih":"April","disadet":"10981"},{"santiye1":"Akkuyu1","tarih":"May","disadet":"4384"},{"santiye1":"Akkuyu1","tarih":"June","disadet":"8330"},{"santiye1":"Akkuyu1","tarih":"July","disadet":"5037"},{"santiye1":"Akkuyu1","tarih":"August","disadet":"6730"},{"santiye1":"Akkuyu1","tarih":"September","disadet":"3523"}]

CodePudding user response:

From the data that you provided I have created a example

import 'package:dio_json_parsing/model.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PageThree(),
    );
  }
}

class PageThree extends StatefulWidget {
  final String url;

  const PageThree({this.url});

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

class _PageThreeState extends State<PageThree> {
  var chart;

  Future<List<Hakedis>> getChartData(widget) async {
    //final jsonEndpoint = "https://securityconcern.php";
    //final response = await get(jsonEndpoint);
    // Above where you fetch the data
    final List<dynamic> data = dataFromJson(jsonString);
    return data;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('GraphTest'),
        ),
        body: Padding(
          padding: EdgeInsets.all(8.0),
          child: FutureBuilder<List>(
            future: getChartData(widget),
            builder: (context, dataapi) {
              if (dataapi.hasError) print(dataapi.error);
              return dataapi.hasData
                  ? ShowChart(data: dataapi.data)
                  : Center(child: CircularProgressIndicator());
            },
          ),
        ),
      ),
    );
  }
}

class ShowChart extends StatelessWidget {
  final List<Hakedis> data;

  ShowChart({this.data});

  List<charts.Series<dynamic, num>> _createSampleData(dataAPI) {
    return [
      new charts.Series<Hakedis, num>(
        id: 'dis adet',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        areaColorFn: (_, __) =>
            charts.MaterialPalette.blue.shadeDefault.lighter,
        //x-axis
        domainFn: (Hakedis hakedis, int number) {
          return number;
        },
        //y-axis
        measureFn: (Hakedis hakedis, _) =>
            double.tryParse(hakedis.disadet).round(),
        data: dataAPI,
      )
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: charts.LineChart(
        _createSampleData(data),
        defaultRenderer:
            new charts.LineRendererConfig(includeArea: true, stacked: true),
        animate: true,
        domainAxis: charts.NumericAxisSpec(
          tickProviderSpec:
              charts.BasicNumericTickProviderSpec(zeroBound: false),
        ),
      ),
    );
  }
}

String jsonString = '''[
   {
      "santiye1":"TSK_Ankara",
      "tarih":"August",
      "disadet":"1252"
   },
   {
      "santiye1":"TSK_Ankara",
      "tarih":"September",
      "disadet":"6528"
   },
   {
      "santiye1":"KMO_Istanbul",
      "tarih":"August",
      "disadet":"4382"
   },
   {
      "santiye1":"KMO_Istanbul",
      "tarih":"September",
      "disadet":"3317"
   },
   {
      "santiye1":"izmit",
      "tarih":"January",
      "disadet":"400"
   },
   {
      "santiye1":"izmit",
      "tarih":"February",
      "disadet":"7883"
   },
   {
      "santiye1":"izmit",
      "tarih":"March",
      "disadet":"9601"
   },
   {
      "santiye1":"izmit",
      "tarih":"April",
      "disadet":"25692"
   },
   {
      "santiye1":"izmit",
      "tarih":"May",
      "disadet":"15714"
   },
   {
      "santiye1":"izmit",
      "tarih":"June",
      "disadet":"28024"
   },
   {
      "santiye1":"izmit",
      "tarih":"July",
      "disadet":"18179"
   },
   {
      "santiye1":"izmit",
      "tarih":"December",
      "disadet":"3612"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"April",
      "disadet":"10981"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"May",
      "disadet":"4384"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"June",
      "disadet":"8330"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"July",
      "disadet":"5037"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"August",
      "disadet":"6730"
   },
   {
      "santiye1":"Akkuyu1",
      "tarih":"September",
      "disadet":"3523"
   }
]''';

Model for the api :

//     final data = dataFromJson(jsonString);

import 'dart:convert';

List<Hakedis> dataFromJson(String str) =>
    List<Hakedis>.from(json.decode(str).map((x) => Hakedis.fromJson(x)));

String dataToJson(List<Hakedis> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Hakedis {
  String santiye1;
  String tarih;
  String disadet;

  Hakedis({this.santiye1, this.tarih, this.disadet});

  Hakedis.fromJson(Map<String, dynamic> json) {
    santiye1 = json['santiye1'];
    tarih = json['tarih'];
    disadet = json['disadet'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['santiye1'] = this.santiye1;
    data['tarih'] = this.tarih;
    data['disadet'] = this.disadet;
    return data;
  }
}

Check the example and let me know if it works

  • Related