I want to use the SWAPI API in my flutter project but the snapshot has no data (it's null). No key is needed and when I click on the website I get the json data.
I did everything like in this documentation https://docs.flutter.dev/cookbook/networking/background-parsing.
persons_page.dart:
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:star_wars/models/persons.dart';
class PersonsPage extends StatefulWidget {
const PersonsPage({ Key? key }) : super(key: key);
#override
State<PersonsPage> createState() => _PersonsPageState();
}
class _PersonsPageState extends State<PersonsPage> {
Future<List<Persons>> fetchPersons(http.Client client) async {
final response = await client.get(Uri.parse('https://swapi.dev/api/people/1'));
return compute(parsePersons, response.body);
}
List<Persons> parsePersons(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String,dynamic>>();
return parsed.map<Persons>((json) => Persons.fromJson(json)).toList();
}
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Persons>>(
future: fetchPersons(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
print(snapshot.data);
return const Center(
child: Text("An error has occurred!"),
);
} else if (snapshot.hasData) {
return PersonsList(persons: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
}
class PersonsList extends StatelessWidget {
const PersonsList({ Key? key, required this.persons }) : super(key: key);
final List<Persons> persons;
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: persons.length,
itemBuilder: (context, index) {
return Text("Got it");
},
);
}
}
persons.dart:
class Persons {
final String name;
final String height;
final String mass;
final String hairColor;
final String skinColor;
final String eyeColor;
final String birthYear;
final String gender;
final List films;
final List vehicles;
final List starships;
const Persons({
required this.name,
required this.height,
required this.mass,
required this.hairColor,
required this.skinColor,
required this.eyeColor,
required this.birthYear,
required this.gender,
required this.films,
required this.vehicles,
required this.starships,
});
factory Persons.fromJson(Map<String, dynamic> json) {
return Persons(
name: json['name'] as String,
height: json['height'] as String,
mass: json['mass'] as String,
hairColor: json['hair_color'] as String,
skinColor: json['skin_color'] as String,
eyeColor: json['eye_color'] as String,
birthYear: json['birth_year'] as String,
gender: json['gender'] as String,
films: json['films'] as List,
vehicles: json['vehicles'] as List,
starships: json['starships'] as List,
);
}
}
the console output is:
Reloaded 1 of 632 libraries in 474ms.
I/flutter ( 6328): null
i don't know what is wrong with the code :/
Related
I am creating a Books app in Flutter and I have an Exception in api.dart file which is working fine according to the code. But I am unable to fetch the books and their properties while using the google Books API. I can't figure out why the link is not working. I hope you can help me out. The api key is hidden but I've copied it right. This is the code:
api.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'books.dart';
import 'package:books_app/config.dart';
class BooksApi {
Future<List<Book>> fetchBooks() async {
final response = await http.get(Uri.parse(
'https://www.googleapis.com/books/v1/volumes?key=$apiKey'));
if (response.statusCode == 200) {
// If the call to the API was successful, parse the JSON
List<dynamic> jsonResponse = jsonDecode(response.body)['items'];
return (jsonResponse.map((book) => Book.fromJson(book)).toList());
} else {
throw Exception('Failed to load books');
}
}
}
books.dart
class Book {
final String title;
final String author;
final String description;
final DateTime datePublished;
final String isbn;
final String imageUrl;
Book(
{required this.title,
required this.author,
required this.description,
required this.datePublished,
required this.isbn,
required this.imageUrl});
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
title: json['volumeInfo']['title'],
author: json['volumeInfo']['author'][0],
description: json['volumeInfo']['description'],
datePublished: json['volumeInfo']['datePublished'],
isbn: json['volumeInfo']['ISBN'],
imageUrl: json['volumeInfo']['imageLinks']['thumbnail']);
}
}
main.dart
import 'package:books_app/api.dart';
import 'package:flutter/material.dart';
import 'books.dart';
final booksAPI = BooksApi();
void main() {
runApp(const MyApp());
}
class DisplayBooks extends StatefulWidget {
const DisplayBooks({super.key});
#override
State<DisplayBooks> createState() => _DisplayBooksState();
}
class _DisplayBooksState extends State<DisplayBooks> {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Book>>(
future: booksAPI.fetchBooks(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data![index].title),
subtitle: Text(snapshot.data![index].author),
leading: Image.network(snapshot.data![index].imageUrl),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const CircularProgressIndicator();
},
);
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const Scaffold(body: DisplayBooks()),
debugShowCheckedModeBanner: false,
title: 'BooksApp',
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: Colors.black),
);
}
}
This is the response code:
response code
Your are missing the query in the api call for volumes. Because just calling volumes won't return anything. And your status, 400 is a "Bad Request" and that indicates that the server could not understand the requested call.
?q=query&
https://www.googleapis.com/books/v1/volumes?q=$query&key=$apiKey
So you need to pass in a query for to fetch all the books you want.
Google Books API just won't let you return all of their billions of books, you need to pass a query and narrow it down to languages, genre, etc.
Read more here, for what queries you can do
Google Books api query documentation
Then You need to pass the books into your model and make sure you're not missing any field or if a field can be missing make sure that field is then optional. And your DateTime should be string because the json you receive doesn't contain any DateTime objects so you need to convert that response into datetime in your code.
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;
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 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
So I'm trying to build a list (of any kind) from a Json list object in flutter, I'm getting it using REST api the response is a Json list with the fields: type, contact {first_name, last_name}, created_at, uuid.
using this code I'm fetching the data and parsing it to custom data type
import 'dart:convert';
import 'package:connectix/models/calls.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class ContactService {
static String _url = "https://api.voipappz.io/tasks//connectix_conversations_recent";
static Future browse() async{
var channel = IOWebSocketChannel.connect(Uri.parse(_url));
}
}
List<CallType> parseCalls(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<CallType>((json) => CallType.fromJson(json)).toList();
}
Future<List<CallType>> fetchCalls(http.Client client) async {
final response = await client
.get(Uri.parse("https://api.voipappz.io/tasks//connectix_conversations_recent"));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseCalls, response.body);
}
That's the data type model
class CallType {
final String type;
final String first_name, last_name;
final String created;
CallType({
required this.type,
required this.first_name,
required this.last_name,
required this.created,
});
factory CallType.fromJson(Map<String, dynamic> json){
return CallType(
type: json['type'],
first_name: json['contact.first_name'],
last_name: json['contact.last_name'],
created: json['created_at'],
);
}
}
and this is the code for the widget I'm trying to display and returns me the error in the question title
class CallsList extends StatelessWidget {
final List<CallType> calls;
CallsList({Key? key, required this.calls}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: calls.length,
itemBuilder: (context, index) {
return Text(calls[index].type);
},
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.orange,
appBar: AppBar(
title: Text('hello'),
),
body: FutureBuilder<List<CallType>>(
future: fetchCalls(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? CallsList(calls: snapshot.data!)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
You marked all attributes of CallType as required. It looks like the API is not returning data for one (or more) of these attributes.
You need either to mark them as optional (remove required and make them of type String?), or take care that your API is always responding with data.