trying to make json request from worldtime api flutter - json

I am trying to make a JSON request from world time API by using future builder when I tried to get the data from my asset folder which contains JSON data it works properly but when I try to get the data from the internet it crashes
here as you can see
this the main class
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
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(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green,
body: FutureBuilder(
future:
get('http://api.worldweatheronline.com/premium/v1/weather.ashx?key=65dbd1979bd445e58aa171529203010&q=Europe/London&format=json&num_of_days=1'),
builder: (context, snapshot) {
var myData = json.decode(snapshot.data.toString());
String jsonsDataString = myData.body.toString(); // toString of Response's body is assigned to jsonDataString
jsonsDataString = jsonDecode(jsonsDataString);
if (myData == null){
return Center(
child: Text(
'Loading',
style: TextStyle(fontSize: 30, color: Colors.red),
),
);
}else{
return Center(
child: Text(
myData,
style: TextStyle(fontSize: 30, color: Colors.red),
),
);
}
}));
}
}
this the error when I try to run the app
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FormatException was thrown building FutureBuilder<Response>(dirty, state: _FutureBuilderState<Response>#2a0b7):
Unexpected character (at character 1)
Instance of 'Response'
^
The relevant error-causing widget was:
FutureBuilder<Response> file:///F:/FlutterProjects/learn_json/lib/main.dart:54:15
When the exception was thrown, this was the stack:
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:31:10)
#4 JsonDecoder.convert (dart:convert/json.dart:495:36)
...

your key is not working , check it using Postman , and you have to await for the response

Related

Flutter exception: Invalid image data using Image.memory()

I am trying to get image from MySQL and display using 'Image.memory' in flutter, but there is exception saying invalid image data:
E/FlutterJNI(12873): Failed to decode image
E/FlutterJNI(12873): android.graphics.ImageDecoder$DecodeException: Failed to create image decoder with message 'unimplemented'Input contained an error.
E/FlutterJNI(12873): at android.graphics.ImageDecoder.nCreate(Native Method)
E/FlutterJNI(12873): at android.graphics.ImageDecoder.access$200(ImageDecoder.java:173)
E/FlutterJNI(12873): at android.graphics.ImageDecoder$ByteBufferSource.createImageDecoder(ImageDecoder.java:250)
E/FlutterJNI(12873): at android.graphics.ImageDecoder.decodeBitmapImpl(ImageDecoder.java:1862)
E/FlutterJNI(12873): at android.graphics.ImageDecoder.decodeBitmap(ImageDecoder.java:1855)
E/FlutterJNI(12873): at io.flutter.embedding.engine.FlutterJNI.decodeImage(FlutterJNI.java:431)
Reloaded 1 of 675 libraries in 750ms.
======== Exception caught by image resource service ================================================
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
Below is my main.dart, when I run the code, the screen shows invalid image data:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'mysql.dart';
import 'dart:convert';
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: MyHomePage(title: 'Flutter and Mysql Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
String title ='';
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var db = new Mysql();
var ques = '';
void _getCustomer() {
db.getConnection().then((conn) {
String sql = 'select question from quiz where quizID =1;';
conn.query(sql).then((results) {
for(var row in results){
setState(() {
ques = row[0]; //<=Here
});
}
});
conn.close();
});
}
#override
Widget build(BuildContext context) {
Uint8List code=base64Decode(ques);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child:Image.memory(base64.decode('ques')),
),
/*Text(
'$ques',
),*/
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _getCustomer,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
This is the output:(https://i.stack.imgur.com/ca32r.png)
When I change the ques = row[0] to ques=row['question'].toString(), the output different and another exception comes out:
Invalid character (at character 1)
Has anyone run into the same problem? I would appreciate if you could help

NoSuchMethodError: The method '[]' was called on null - Flutter

I want to read data from this JSON in this way (PLEASE READ CODE COMMENTS):
class Profile extends StatefulWidget {
final id;
Profile({Key? key, #required this.id}) : super(key: key);
#override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
var data;
#override
void initState() {
super.initState();
void getData() async {
Response response = await get(
Uri.parse('https://en.gravatar.com/' + widget.id + '.json'));
this.data = json.decode(utf8.decode(response.bodyBytes));
// READ PLEASE >>> Data successfully is loaded from server & if you
// print this.data it will show full data in console <<< READ PLEASE
}
getData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Profile | MWX Gravatar Viewer',
home: Scaffold(
appBar: AppBar(
title: Text('Profile | MGV'),
),
body: Center(
child: Column(
children: [
Text(this.data['entry'][0]['name']['familyName']), // Where raises error
],
),
),
),
);
}
}
And i get this error while rendering page:
The following NoSuchMethodError was thrown building Profile(dirty, state: _ProfileState#35267):
The method '[]' was called on null.
Receiver: null
Tried calling: []("entry")
NOTE: After a hot reload error is gone & I CAN SEE THE DATA I NEEDED ON SCREEN but every time when I want to load the page this error will be shown although I can see what I expected, after a hot reload
Your body might be running and not waiting for your getData() on initState. Try to check if it's null before using it:
body: Center(
child: Column(
children: [
Text(this.data != null ? this.data['entry'][0]['name']['familyName'] : 'no data'), // Where raises error
],
),
),
Or use a FutureBuilder.
This is because you are calling network request and at same time you are using data which is null by default so you can use either FutureBuilder() or handle error by null check

_TypeError was thrown building FutureBuilder<dynamic>(dirty, state: _FutureBuilderState<dynamic> type 'Null' is not a subtype of type 'List<dynamic>'

#
I've been dealing with this problem for a long time.
I am trying to parse JSON and convert it into list view.
I am getting the response body and it is been converted to list also but its sending null to the future builder, I am getting this error:
#
Exception caught by widgets library =======================================================
The following _TypeError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#a289a):
type 'Null' is not a subtype of type 'List'
The relevant error-causing widget was:
FutureBuilder<dynamic> file:///Users/metehanmacbook/StudioProjects/flutter_mysql/lib/main.dart:37:13
When the exception was thrown, this was the stack:
#0 _MyHomePageState.build.<anonymous closure> (package:flutter_mysql/main.dart:40:14)
#1 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:775:55)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4746:11)
...
**# Codes: #**
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
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 MySql',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.lime,
),
home: MyHomePage(title: 'Flutter MYSQL'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: Getmethod(),
builder: (BuildContext context, AsyncSnapshot snapshot){
List snap = snapshot.data;
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
}
if(snapshot.hasError){
return Center(
child: Text('error fatch'),
);
}
return ListView.builder(
itemCount: snap.length,
itemBuilder: (context, index){
return ListTile(
title: Text("Product Name: ${snap[index]['pro_name']}"),
subtitle: Text("Product Desc: ${snap[index]['pro_desc']}"),
);
}
);
},
),
);
}
Getmethod()async{
String theurl = ('http://10.0.2.2/flutter-demo/getdata.php');
var res = await http.get(Uri.parse(Uri.encodeFull(theurl)),headers: {"Accept":"application/json"});
var responseBody = json.decode(res.body);
print(responseBody);
return responseBody;
}
}
how can i solve this problem?
Seems like error is List snap = snapshot.data; snapshot.data is null, and you want to cast it to list.
Solutions:
You can make your snap variable as nullable: List? snap = snapshot.data;
You can return default value (empty list for example) if snap returns null: List snap = snapshot.data ?? [];
Investigate why your Getmethod returns null;

how to open a 'csv file' like 'url launcher' in Flutter

i converted list into File of .csv extension then
tried OpenFile.open and ended up with error No permissions found in manifest for: 2, tried canLaunch and ended up with error name.csv exposed beyond app through Intent.getData(), Failed to handle method call
so how to open that csv file in any 3rd part application.
You can copy paste run full code below
and make sure you have a file /sdcard/Download/sample.csv, see picture below
You also need CSV Viewer installed in your Emulator
code snippet
final filePath = '/sdcard/Download/sample.csv';
print('${filePath}');
final message = await OpenFile.open(filePath);
working demo
device file explorer
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:open_file/open_file.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _openResult = 'Unknown';
Future<void> openFile() async {
//final filePath = '/sdcard/Download/sample.pdf';
final filePath = '/sdcard/Download/sample.csv';
print('${filePath}');
final message = await OpenFile.open(filePath);
setState(() {
_openResult = message;
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('open result: $_openResult\n'),
FlatButton(
child: Text('Tap to open file'),
onPressed: openFile,
),
],
),
),
),
);
}
}

Flutter doesn't want to import json

I am trying to follow this official tutorial in order to make a web request to an url: https://flutter.io/cookbook/networking/fetch-data/
I have thus added these lines in pubspec.yaml:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: 0.11.3+17
json_annotation: ^0.2.3
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^0.9.0
json_serializable: ^0.5.4
and when compiling, I got this error.
Compiler message: lib/main.dart:53:26: Error: Method not found:
'decode'.
return Post.fromJson(json.decode(response.body));
Any idea what I am doing wrong?
Here is my code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo2',
theme: new ThemeData(
primarySwatch: Colors.amber,
),
home: new MyHomePage(title: 'Islam Essentiel'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(widget.title),
),
body: new Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: new Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug paint" (press "p" in the console where you ran
// "flutter run", or select "Toggle Debug Paint" from the Flutter tool
// window in IntelliJ) to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: const Icon(Icons.album),
title: const Text('al-khamis: 30. Muharram 1440'),
subtitle: const Text('20:51 - Icha.'),
),
new ButtonTheme.bar( // make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('MECQUE - DIRECTION'),
onPressed: () { /* ... */ },
),
],
),
),
],
),
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: fetchPost,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
You need to import it
import 'dart:convert' show jsonDecode;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
...
and use it with
jsonDecode(response.body)
or
import 'dart:convert' show json;
with
json.decode(response.body)
The first variant was added to avoid conflicts when the variable holding the JSON value is named json.