I have tried to put JSON data in flutter chart, I used syncfusion_flutter_charts library but its not working and its only showing y axis point but not x axis points any one can help me the display json data in flutter SfCartesianChart
Or
help me in put this data in other charts of flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:syncfusion_flutter_charts/charts.dart';
class Graph extends StatefulWidget {
#override
_GraphState createState() => _GraphState();
}
class _GraphState extends State<Graph> {
Future<String> fetchUsers() async {
String url = 'http://example.com/json.php';
var response = await http.get(url);
print(response.body);
return response.body.toString();
}
#override
void initState() {
loadSalesData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Graph"),
),
body: SfCartesianChart(
title: ChartTitle(text: 'Leads'),
primaryXAxis: CategoryAxis(),
series: <LineSeries<LinearSales, String>>[
LineSeries<LinearSales, String>(
dataSource: chartData,
xValueMapper: (LinearSales sales, _) => sales.name,
yValueMapper: (LinearSales sales, _) => sales.leads,
)
]));
}
List<LinearSales> chartData = [];
Future loadSalesData() async {
final jsonResponse = json.decode(jsonString);
// print(jsonString);
// print(jsonResponse);
setState(() {
for (Map i in jsonResponse) chartData.add(LinearSales.fromJson(i));
});
}
}
class LinearSales {
LinearSales(this.name, this.leads);
final String name;
final int leads;
factory LinearSales.fromJson(Map<String, dynamic> parsedJson) {
//print(parsedJson);
return LinearSales(
parsedJson['name'],
parsedJson['leads'],
);
}
}
I resolve this problem. refer int.parse()
class LinearSales {
LinearSales(this.name, this.leads);
final String name;
final int leads;
factory LinearSales.fromJson(Map<String, dynamic> parsedJson) {
//print(parsedJson);
return LinearSales(
parsedJson['name'],
int.parse(parsedJson['leads']),
);
}
}
Related
I want to draw a line chart catching the data from a JSON file. The JSON is inside the assets folder. But I do not know How to Develop a Line Chart using my JSON Data. Can please somebody help and guide me. Thank you very much.
Here is the JSON
{
"measure": [
{
"count": 8,
"range_array": [20.6, 27.9, 50.6],
"force_array": [116.8, 187.4, 226.6]
}
]
}
Here is the Model
class DataModel {
DataModel({this.measure});
List<DataTitle>? measure;
factory DataModel.fromJson(Map<String, dynamic> json) {
return DataModel(
measure: List<DataTitle>.from(
json['measure'].map((c) => DataTitle.fromJson(c)).toList()),
);
}
}
class DataTitle {
DataTitle(
{required this.number,
required this.firstarray,
required this.secondarray});
int? number;
List<double>? firstarray;
List<double>? secondarray;
DataTitle.fromJson(Map<String, dynamic> json) {
number = json['count'];
firstarray = json['range_array'] == null
? []
: List<double>.from(json['range_array'].map((x) => x.toDouble()));
secondarray = json['force_array'] == null
? []
: List<double>.from(json['force_array'].map((x) => x.toDouble()));
}
#override
String toString() {
return 'DATA TITLE{Count: $number, RangeArray: $firstarray, ForceArray: $secondarray}';
}
}
Here is the where i want to display the Chart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:read_local_json/measure_data_model.dart';
import 'dart:async' show Future;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'JSON',
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
Future loadData() async {
final jsonString = await rootBundle.loadString('assets/measurelist.json');
final decodedJson = json.decode(jsonString);
List<DataTitle> dataTileList = (decodedJson['measure'] as List)
.map((jsonElement) => DataTitle.fromJson(jsonElement))
.toList();
print(dataTileList.first);
print(dataTileList.last);
}
#override
void initState() {
super.initState();
loadData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('JSON Chart'),
),
body: const Center(
child: Text('JSON Chart'),
),
);
}
}
The JSON data can be converted to a list with the help of the json.decode function.
import 'dart:convert';
final List<Measure> measures = (json.decode(jsonstring)['measure'] as List).map((i) => Measure.fromJson(i)).toList();
class Measure {
final int count;
final List<double> range_array;
final List<double> force_array;
Measure({this.count, this.range_array, this.force_array});
factory Measure.fromJson(Map<String, dynamic> json) {
return Measure(
count: json['count'],
range_array: json['range_array'],
force_array: json['force_array'],
);
}
}
After that, use a charts package to draw the line chart.
LineChart(
data: LineChartData(
points: measures[0].count.toList().asMap().entries.map((key) => DataPoint(key.key.toDouble(), measures[0].force_array[key.key])).toList(),
),
);
There is a flutter application that I wrote below. I'm trying to connect to mysql database and pull data with api, but every time I try, I get an error like the following. The model codes to which it is linked are also available below.
NoSuchMethodError (NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Receiver: _LinkedHashMap len:3
Tried calling: cast<Map<String, dynamic>>()
Found: cast<Y0, Y1>() => Map<Y0, Y1>) I am getting this error. How can I fix.
import 'package:dbconnecttest/data.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: main1(),
);
}
}
class main1 extends StatefulWidget {
main1({Key? key}) : super(key: key);
#override
State<main1> createState() => _main1State();
}
class _main1State extends State<main1> {
Future<List<data>>? futuredata;
#override
void initState() {
// TODO: implement initState
futuredata = fetchPost();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fake Friends"),
backgroundColor: Colors.green,
),
body: FutureBuilder<List<data>>(
future: futuredata,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (_, index) => Container(
child: Text("${snapshot.data![index].autid}"),
),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
Future<List<data>> fetchPost() async {
final response =
await http.get(Uri.parse('http://192.168.1.108/server/data.php'));
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
return parsed.map<data>((json) => data.fromJson(json)).toList();
} else {
throw Exception('Failed');
}
}
import 'dart:convert';
List<data> postFromJson(String str) =>
List<data>.from(json.decode(str).map((x) => data.fromJson(x)));
class data {
int? id;
String? autid;
String? status;
String? startdate;
String? finishdate;
data(
{required this.id,
required this.autid,
required this.status,
required this.startdate,
required this.finishdate});
data.fromJson(Map<String, dynamic> json) {
id = json['id'];
autid = json['autid'];
status = json['status'];
startdate = json['startdate'];
finishdate = json['finishdate'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['autid'] = this.autid;
data['status'] = this.status;
data['startdate'] = this.startdate;
data['finishdate'] = this.finishdate;
return data;
}
}
Try this
Map<String, dynamic>.from(data)
of course i can share. this is my flutter doctor
I'm trying to parse an array of JSON Objects to populate a GridView in Flutter.
So far, I can only get a single object, but can't traverse the whole array of objects.
JSON String: A list of Beef recipe objects within 'beef' array.
My code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class SpecificCategoryPage extends StatefulWidget {
late final String category;
SpecificCategoryPage({Key? key, required this.category}) : super(key: key);
#override
_SpecificCategoryPageState createState() => _SpecificCategoryPageState();
}
class _SpecificCategoryPageState extends State<SpecificCategoryPage> {
late Future<Meal> meals;
late List<Widget> mealCards;
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<Meal>(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
'Truest\nId: ${snapshot.data!.id}. ${snapshot.data!.meal}');
} else {
return Text('${snapshot.error}');
}
// Be default, show a loading spinner.
return CircularProgressIndicator();
},
future: meals,
),
);
}
#override
void initState() {
super.initState();
meals = _fetchMeals();
}
Future<Meal> _fetchMeals() async {
final http.Response mealsData = await http.get(
Uri.parse('https://www.themealdb.com/api/json/v1/1/filter.php?c=Beef'));
if (mealsData.statusCode == 200)
return Meal.fromJson(jsonDecode(mealsData.body));
else
throw Exception('Failed to load meals');
}
class Meal {
final String? id, meal;
Meal({required this.id, required this.meal});
factory Meal.fromJson(Map<String, dynamic> json) {
return Meal(
id: json['meals'][0]['idMeal'], meal: json['meals'][0]['strMeal']);
}
}
Sample object traversal path:
{"meals":[{"strMeal":"Beef and Mustard Pie","strMealThumb":"https:\/\/www.themealdb.com\/images\/media\/meals\/sytuqu1511553755.jpg","idMeal":"52874"}, {object1}, {object2}]}
What I'm getting:
{"strMeal":"Beef and Mustard
Pie","strMealThumb":"https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal":"52874"}
How do I get all objects in the array and inflate the GridView widget?
import 'dart:convert';
// First you should create a model to represent a meal
class Meal {
// Place all the meal properties here
final String strMeal;
final String strMealThumb;
final String idMeal;
// Create a constructor that accepts all properties. They can be required or not
Meal({
required this.strMeal,
required this.strMealThumb,
required this.idMeal,
});
// Create a method (or factory constructor to populate the object based on a json input)
factory Meal.fromJson(Map<String, dynamic> json) => Meal(
strMeal: json['strMeal'],
strMealThumb: json['strMealThumb'],
idMeal: json['idMeal'],
);
String toString() {
return 'strMeal: $strMeal, strMealThumb: $strMealThumb, idMeal: $idMeal';
}
}
/// Then you should create another object to represent your response
/// It holds a list of meals that'll be populated by your API response
class YourAPIResponse {
final List<Meal> meals;
YourAPIResponse({required this.meals});
factory YourAPIResponse.fromJson(Map<String, dynamic> json) =>
YourAPIResponse(
meals: List<Meal>.from(
json['meals'].map((meal) => Meal.fromJson(meal)),
),
);
}
void main() {
// Test data: This will be your API response
String jsonString = '{"meals": [{"strMeal": "Beef and Mustard Pie","strMealThumb": "https://www.themealdb.com/images/media/meals/sytuqu1511553755.jpg","idMeal": "52874"}]}';
final apiResponse = YourAPIResponse.fromJson(json.decode(jsonString));
// Your meals list
// You can use this to populate the gridview
print(apiResponse.meals);
}
Try something like:
...
return jsonDecode(mealsData.body)['meals'].map((meal) => Meal.fromJson(meal)).toList();
...
class Meal {
final String? id, meal;
Meal({required this.id, required this.meal});
factory Meal.fromJson(Map<String, dynamic> json) {
return Meal(
id: json['idMeal'], meal: json['strMeal']);
}
}
This iterates the meals in your response body and maps them to a List of Meals.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class HomePage extends StatefulWidget {
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
List items;
Future<String> getData() async {
var response = await http.get(
'https://api.torn.com/torn/?selections=items&key=7PnSA9HkVB5B6eAK');
this.setState(() {
Map items = json.decode(response.body);
print(items);
});
}
#override
void initState() {
this.getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: items == null ? 0 : items.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Text(items[index]['name']),
);
},
),
);
}
}
As far as i know we can get Json in two forms, first is List and second is a Map.
In my case i received a Map with all data i need but unfortunately i dont know how properly display that.
From print i received data but nothing happen on screen.
You must not re-define items. You need to set it. It will look like this:
setState(() {
items = jsonDecode(response.body);
print(items);
});
Check the setState inside your getData method, you are creating a new items variable instead of assigning the new value to it. Try this one.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class HomePage extends StatefulWidget {
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
Map items = {};
Future<void> getData() async {
http.Response res = await http.get(
"https://api.torn.com/torn/?selections=items&key=7PnSA9HkVB5B6eAK",
);
setState(() => items = jsonDecode(res.body)["items"]);
print(items);
}
#override
void initState() {
getData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
index++;
return Card(
child: Text(items[index.toString()]["name"] ?? "Empty"),
);
},
),
);
}
}
I'm a very beginner at Flutter development, in the code below I tried to get data from here and display it in ListView :
static final String URL = "https://corona.lmao.ninja/countries";
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
var jsonData = json.decode(data.body);
print("the count is: " + jsonData.toString()); //Data successfully printed
List<CoronaModel> listCoronaCountries = [];
for (var item in jsonData) {
CoronaModel mCorona = CoronaModel(
item["country"],
item["recovered"],
item["cases"],
item["critical"],
item["deaths"],
item["todayCases"],
item["todayDeaths"]);
listCoronaCountries.add(mCorona);
}
if (listCoronaCountries.length > 0) {
print("the count is: " + listCoronaCountries.length.toString());
} else {
print("EMPTY");
}
return listCoronaCountries;
}
At run time, the first print works, I can see the data successfully printed, but the IF statement is not showing
if (listCoronaCountries.length > 0) {
print("the count is: " + listCoronaCountries.length.toString());
} else {
print("EMPTY");
}
Model :
class CoronaModel {
final String country;
final String recovered;
final String cases;
final String critical;
final String deaths;
final String todayCases;
final String todayDeaths;
CoronaModel(this.country, this.recovered, this.cases, this.critical,
this.deaths, this.todayCases, this.todayDeaths);
}
You can copy paste run full code below
You can parse with coronaModelFromJson and display with FutureBuilder
code snippet
List<CoronaModel> coronaModelFromJson(String str) => List<CoronaModel>.from(
json.decode(str).map((x) => CoronaModel.fromJson(x)));
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
List<CoronaModel> listCoronaCountries = coronaModelFromJson(data.body);
return listCoronaCountries;
}
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final coronaModel = coronaModelFromJson(jsonString);
import 'dart:convert';
List<CoronaModel> coronaModelFromJson(String str) => List<CoronaModel>.from(
json.decode(str).map((x) => CoronaModel.fromJson(x)));
String coronaModelToJson(List<CoronaModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CoronaModel {
String country;
int cases;
int todayCases;
int deaths;
int todayDeaths;
int recovered;
int active;
int critical;
int casesPerOneMillion;
CoronaModel({
this.country,
this.cases,
this.todayCases,
this.deaths,
this.todayDeaths,
this.recovered,
this.active,
this.critical,
this.casesPerOneMillion,
});
factory CoronaModel.fromJson(Map<String, dynamic> json) => CoronaModel(
country: json["country"],
cases: json["cases"],
todayCases: json["todayCases"],
deaths: json["deaths"],
todayDeaths: json["todayDeaths"],
recovered: json["recovered"],
active: json["active"],
critical: json["critical"],
casesPerOneMillion: json["casesPerOneMillion"],
);
Map<String, dynamic> toJson() => {
"country": country,
"cases": cases,
"todayCases": todayCases,
"deaths": deaths,
"todayDeaths": todayDeaths,
"recovered": recovered,
"active": active,
"critical": critical,
"casesPerOneMillion": casesPerOneMillion,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static final String URL = "https://corona.lmao.ninja/countries";
Future _future;
Future<List<CoronaModel>> getData() async {
var data = await http.get(URL);
List<CoronaModel> listCoronaCountries = coronaModelFromJson(data.body);
return listCoronaCountries;
}
#override
void initState() {
// TODO: implement initState
super.initState();
_future = getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<List<CoronaModel>>(
future: _future,
builder: (BuildContext context,
AsyncSnapshot<List<CoronaModel>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
' ${snapshot.data[index].country} , ${snapshot.data[index].cases}'),
);
});
}
}
}));
}
}
Instead of hand coding '.fromJson/.toJson' methods. you could rely on
this library https://github.com/k-paxian/dart-json-mapper,
It will help you not only for this case, but for all Dart Object => JSON => Dart Object cases.