How to read a list from json object in flutter? - json

I have data in json format where one field subtitle has list of data again. How can I iterate through this list which already inside a list. here is the code.
#Data.json
[
{
"id":0,
"title":"Heading",
"subtitle":[
"sub1",
"sub2",
"sub3"
]
},
{
"id":1,
"title":"Heading1",
"subtitle":[
"sub4",
"sub5",
"sub6"
]
},
{
"id":2,
"title":"Heading2",
"subtitle":[
"sub7",
"sub8",
"sub9"
]
}
]
#list.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(new MaterialApp(
home: new HomePage()
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class Location {
final String id;
final double lat;
final double long;
Location({this.id, this.lat, this.long});
}
class HomePageState extends State<HomePage> {
List data;
Future _future;
List<Location> locations;
Future<String> getData() async {
var response = await rootBundle.loadString('asset/sample.json');
this.setState(() {
data = jsonDecode(response);
});
for(var i=0; i< data.length; i++){
print( data[i]["subtitle"]);
}
return "Success!";
}
#override
void initState(){
this.getData();
}
#override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(title: new Text("Listviews"), backgroundColor: Colors.blue),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index){
return new Card(
child: new Text(data[index]["title"]),
);
},
),
);
}
}
I want to list the items in subtitle. How can I do it?

You can do something like this with a column for example:
Column(children: [
for ( var subtitle in data[index]['subtitle'] ) Text(subtitle)
],
),

Related

Reading specific items from json in flutter

Hi I have json containing almost 30 items I just waan display only 10 itmes in listview and on every time I refresh page should change (in other words random items) should be selected from the json.
Is ther any way and would be great If someone can show with example.
Thanks
Put json file in a folder called assets:
Image
Add this to pubspec.yaml:
assets:
- assets/
Image
main.dart file:
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List items = [];
int itemCount = 2;
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/items.json');
final data = await json.decode(response);
setState(() {
items = data["items"];
});
}
#override
void initState() {
super.initState();
readJson();
}
String randomItem() {
int random = Random().nextInt(items.length);
print(random);
String item = items[random]["item"];
List newItems = [];
for(int i = 0; i < items.length; i++){
if(item != items[i]["item"]){
newItems.add(items[i]);
}
}
items = [...newItems];
return item;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Title"),
),
body:
items.isNotEmpty ? Center(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: itemCount,
itemBuilder: (context, index) => Column(
children: [
Text(randomItem()),
],
),
),
): const Text("Loading..."),
);
}
}
Json file:
{
"items": [
{
"item": "One"
},
{
"item": "Two"
},
{
"item": "Three"
}
]
}
This picks two random items which are strings from the json file.
The itemCount variable can't be longer than the number of items in the json file. Change it to 10 if you want 10 different items.

How to show JSON Data in Line Chart in Flutter?

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(),
),
);

how to read local json file in flutter

I am trying to read a local json file named "catalog.json" I wrote all the nessessary codes but it's showing this error "lateinitializationError: Field 'catalogdata' has not been initialized."
then i tried by initializing the 'catalogdata' variable but then it shows that 'catalogdata' variable is empty . I dont know how to solve it . Please help me.
my code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
late List catalogdata;
Future<String> loadData() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
setState(() {
catalogdata = json.decode(data);
});
return "success";
}
#override
void initState() {
// TODO: implement initState
this.loadData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Homepage"),
),
body: Center(
child: Text(
catalogdata[0],
style: TextStyle(fontSize: 20),
),
),
);
}
}
Here’s sample.json:
{
"items": [
{
"id": "p1",
"name": "Item 1",
"description": "Description 1"
},
{
"id": "p2",
"name": "Item 2",
"description": "Description 2"
},
{
"id": "p3",
"name": "Item 3",
"description": "Description 3"
}
]
}
The code which is used to fetch data from the JSON file (see the full code below):
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
// ...
}
Declare the json file in the assets section in your pubspec.yaml file:
flutter:
assets:
- assets/sample.json
main.dart
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List _items = [];
// Fetch content from the json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
setState(() {
_items = data["items"];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Kindacode.com',
),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
ElevatedButton(
child: const Text('Load Data'),
onPressed: readJson,
),
// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["id"]),
title: Text(_items[index]["name"]),
subtitle: Text(_items[index]["description"]),
),
);
},
),
)
: Container()
],
),
),
);
}
}
it's showing this error "lateinitializationError: Field 'catalogdata'
has not been initialized." then I tried by initializing the
'catalogdata'
While using late before variables make sure that, the variable must be initialized later. Otherwise, you can encounter a runtime error when the variable is used.
If you didn't add the correct location catalog.json in pubsec.yaml your variable catalog didn't gets the correct value so the late variable is not initialized.
So you must add asset path in pubsec.yaml
assets:
- assets/
- assets/images/files/catalog.json
Another case here is JSON.decode() return map<string,dynamic> value here you set list.maybe that also cause the problem and not initialised.
instead of this late List catalogdata; use this late var catalogdata; or late Map<string,dynamic> catalogdata;
Sample Code
Catalog.json
{
"name": "lava",
"Catagory": "man"
}
Main.dart
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class AppRoutes {
static String detail = "/Detail";
static String Page2 = "/FilterBeacon";
static String Page1 = "/FilterPoint";
static String home = "/";
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
// key: constItem.navigatorKey,
initialRoute: "/",
routes: {
AppRoutes.home: (context) => Home(),
},
title: _title,
// home: ,
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
var _index = 0;
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Homepage(),
);
}
}
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
late var catalogdata;
Future<String> loadDatas() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
// setState(() {
catalogdata = json.decode(data);
// });
return "success";
}
Future<String> loadData() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
setState(() {
catalogdata = json.decode(data);
});
return "success";
}
#override
void initState() {
loadData();
// loadData().then((value) => catalogdata=value);
} // String jsons = "";
// #override
// Future<void> initState() async {
// super.initState();
// await loadData();
// }
#override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: loadData(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.connectionState == ConnectionState.done)
return Center(
child: Text(
catalogdata.toString(),
style: TextStyle(),
),
);
else
return Container();
});
return Scaffold(
appBar: AppBar(
title: Text("Homepage"),
),
body: Center(
child: Text(
catalogdata.toString(),
style: TextStyle(),
),
),
);
}
}

Cant transform json to listview in flutter

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"),
);
},
),
);
}
}

Getting data from Json in Flutter

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.