I've been struggling with this for quite a while. I'm just trying to read text from JSON and place it in Text, but it won't allow me, and it only throws out this error which I can't find a solution to.
Error :
I made a separate class quotes.dart which contains only this
final String author;
final String quote;
Quotes({required this.author, required this.quote});
factory Quotes.fromJson(Map<String, dynamic> data) {
return Quotes(author: data["author"], quote: data["quote"]);
}
Map<String, dynamic> toJson() {
return {
"author": author,
"quote": quote,
};
}
}
And in main I've got this:
// ignore_for_file: unnecessary_string_interpolations
import 'quotes.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:todo_task/quotes.dart';
void main() {
runApp(const MaterialApp(
home: todo_task(),
));
}
class todo_task extends StatefulWidget {
const todo_task({Key? key}) : super(key: key);
#override
_todo_taskState createState() => _todo_taskState();
}
class _todo_taskState extends State<todo_task> {
Map<String, dynamic> userMap = jsonDecode('assets/json/quotes.json');
// user = Quotes.fromJson(userMap);
.
.
.
Align(
alignment: Alignment.topRight,
child: Padding(
padding: EdgeInsets.fromLTRB(0.0, 110.0, 5.0, 0.0),
child: Text('${userMap['author']}',
style: TextStyle(
color: Colors.white,
fontSize: 20,
)),
)),
Also, my JSON file is simple
{
"author":"Albert Einstein",
"quote":"We cannot solve problems with the kind of thinking we employed when we came up with them."
}
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(),
),
);
I have a problem with parsed JSON in Flutter-Dart. Actually, there is no problem, but there is a method which I don't know. I'm getting data from a PHP server and I'm writing to listview from parsed JSON. However, I don't want to write to a listview, I just want to get data from the parsed JSON because I will set an another textview from parsed json data which I get.
This is my code.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get(Uri.parse('https://meshcurrent.online/get_20word.php'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
class Photo {
final String questId;
final String quest;
final String ans1;
final String ans2;
final String ans3;
final String ans4;
final String correctAns;
final String category;
const Photo({
required this.questId,
required this.quest,
required this.ans1,
required this.ans2,
required this.ans3,
required this.ans4,
required this.correctAns,
required this.category,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
questId: json['questId'] as String,
quest: json['quest'] as String,
ans1: json['ans1'] as String,
ans2: json['ans2'] as String,
ans3: json['ans3'] as String,
ans4: json['ans4'] as String,
correctAns: json['correctAns'] as String,
category: json['category'] as String,
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(children: [
Text("ronalddo"),
Text("mecsfsi"),
FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
]));
}
}
class PhotosList extends StatelessWidget {
const PhotosList({Key? key, required this.photos}) : super(key: key);
final List<Photo> photos;
#override
Widget build(BuildContext context) {
return ListView.builder(
padding: EdgeInsets.all(20),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: photos.length,
itemBuilder: (context, index) {
return ListTile(
title: Row(
children: [
Text(photos[index].quest),
Text(photos[index].ans1),
],
),
);
});
}
}
I want to do get only first column and get only questId from this parsed JSON. And I will set a textview using Getx library. I know set a data with Getx library but I can't do it because I don't know get the data.
If you just want to get the first questId of the List, do
photos[0].questId;
I am trying o get data from coinmarketcap api but i seem to be getting the error above. included is my main.dart code, this is my first time using flutter/dart, so i don't quite understand everything, i followed this guide from flutter docs https://docs.flutter.dev/cookbook/networking/background-parsing , but i still got some errors that i then tried to solve by following this NoSuchMethodError: Class'_InternalLinkedHashMap<String, dynamic>'has no instance method 'cast' with matching arguments
Can anyone help me?
The error i get is this on line 22:
NoSuchMethodError (NoSuchMethodError: Class 'CastMap<String, dynamic, String, dynamic>' has no instance method 'call'.
Receiver: Instance of 'CastMap<String, dynamic, String, dynamic>'
My dart file:
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Criptos>> fetchcriptos(http.Client client) async {
final response = await client.get(
Uri.parse(
'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'),
headers: {
"X-CMC_PRO_API_KEY": "ecfc8e0a-fd11-422d-8a7b-114e8b31e62c",
"Accept": "application/json"
});
return compute(parsecriptos, response.body);
}
List<Criptos> parsecriptos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<String, dynamic>();
return parsed<Criptos>((json) => Criptos.fromJson(json)).toList();
}
class Criptos {
final int id;
final String name;
final String symbol;
final int max_supply;
final int cmc_rank;
final int preco;
const Criptos({
required this.id,
required this.name,
required this.symbol,
required this.max_supply,
required this.cmc_rank,
required this.preco,
});
factory Criptos.fromJson(Map<String, dynamic> json) {
return Criptos(
id: json['data']['id'] as int,
name: json['data']['name'] as String,
symbol: json['data']['symbol'] as String,
max_supply: json['data']['max_supply'] as int,
cmc_rank: json['data']['cmc_rank'] as int,
preco: json['data']['quote']['USD']['price'] as int);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Criptos>>(
future: fetchcriptos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return ListaCriptos(cripto: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class ListaCriptos extends StatelessWidget {
const ListaCriptos({Key? key, required this.cripto}) : super(key: key);
final List<Criptos> cripto;
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: cripto.length,
itemBuilder: (context, index) {
return Text(cripto[index].id);
},
);
}
}
Github of the project
I am using nodejs and mongodb as the backend I have created model classes but when I am trying to display the Json data its showing error I am not able to solve the error list ' is not a subtype of type 'string' in type cast
I am getting the json data from the backend
my json data and error
addproductmodel class
import 'package:json_annotation/json_annotation.dart';
part 'addproductmodel.g.dart';
#JsonSerializable()
class Addproductmodel {
String username;
String product_name;
String product_details;
String productImage;
String quantity;
String currency;
String unit;
#JsonKey(name: "_id")
String id;
String mrp;
String sp;
String per;
Addproductmodel(
{
this.username,
this.product_name,
this.product_details,
this.productImage,
this.currency,
this.quantity,
this.unit,
this.id,
this.mrp,
this.sp,
this.per,
});
factory Addproductmodel.fromJson(Map<String, dynamic> json) =>
_$AddproductmodelFromJson(json);
Map<String, dynamic> toJson() => _$AddproductmodelToJson(this);
}
supermodel class
import 'package:flutter_app/Model/addproductmodel.dart';
import 'package:json_annotation/json_annotation.dart';
part 'supermodel.g.dart';
#JsonSerializable()
class SuperModel {
List<Addproductmodel> data;
SuperModel({this.data});
factory SuperModel.fromJson(Map<String, dynamic> json) =>
_$SuperModelFromJson(json);
Map<String, dynamic> toJson() => _$SuperModelToJson(this);
}
main function screen
import 'package:flutter/material.dart';
import 'package:flutter_app/Model/addproductmodel.dart';
import 'package:flutter_app/Model/supermodel.dart';
import 'package:flutter_app/NetworkHandler.dart';
import 'package:flutter_app/Product/AddProduct.dart';
import 'package:flutter_app/Product/products.dart';
class ProductScreenTest extends StatefulWidget {
#override
_ProductScreenTestState createState() => _ProductScreenTestState();
}
class _ProductScreenTestState extends State<ProductScreenTest> {
NetworkHandler networkHandler = NetworkHandler();
SuperModel listModel = SuperModel();
List<Addproductmodel> cart= List<Addproductmodel>();
#override
void initState() {
super.initState();
fetchData1();
}
void fetchData1() async {
var response = await networkHandler.get("/add_product/getproducts");
setState(() {
listModel=SuperModel.fromJson(response);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:
Container(
child: listModel.data.length == null ? Center(
child: Text("We don't have any Products Yet"),
) : ListView.builder(itemBuilder: (context,index)=>
dataShow(listModel.data[index]),
itemCount: listModel.data.length == null ? 0 : listModel.data.length,
),
),
);
}
Widget dataShow(Addproductmodel obj){
return
Container(
height: 40,
padding: EdgeInsets.fromLTRB(15, 8, 15, 8),
width: MediaQuery.of(context).size.width,
child: Text(
"${obj.product_name}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
);
}
}
Here is a complete code snippet that should demonstrate the issue that I am bumping into.
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
SystemChrome.setEnabledSystemUIOverlays([]);
runApp(
MaterialApp(
home: MyHomePage(),
),
);
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key,}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
Future<latestVersion> fetchAlbum() async {
final response = await http.get('https://api.jsonbin.io/b/5fd25941bef8b7699e57dce9');
if (response.statusCode == 200) {
print('yay');
return latestVersion.fromJson(jsonDecode(response.body));
} else {
print('nay');
throw Exception('Failed to load version');
}
}
class latestVersion {
final String title;
final String version;
latestVersion({this.version, this.title});
factory latestVersion.fromJson(Map<String, dynamic> json) {
return latestVersion(version: json['version'], title: json['title'],
);
}
}
class _MyHomePageState extends State<MyHomePage> {
static Future<latestVersion> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.yellow,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(''),
Text('CURRENT'),
Text('---------'),
Text('0.37'),
Text(''),
Text('LATEST'),
Text('--------'),
Text(latestVersion.version),
Text(''),
Text(''),
],
),
),
);
}
}
When trying to run this code, I get an error at line 76.
"instance member 'version' cannot be accessed using static access"
How exactly can I access this json-decoded variable? Thank you in advance. I'm new to working with asynchronous functions and Future and would appreciate any help that can be given.
The error means version is not a Static variable. So to access it like this LatestVersion.version either make version a static variable or
Replace
Text(LatestVersion.version),
with
Text(LatestVersion().version),
If everything else is correct in your code the above should work.