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

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

Related

_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;

Flutter : Unable to fetch json file data from an api

Hello Everyone I am new to flutter during practicing While trying to fetch JSON data from an api I am unable to complete the operation and receiving the below mentioned error. I have attached my entire program and error notification for your suggestions.
What this program is about?
I am trying to fetch the cryptocurrency price details from an api and trying to display the few details of that website in my app. while doing that the data type which i mentioned in the code creating some error and i tried to change the data type and other things but still it is not solved.
main.dart
import 'package:flutter/material.dart';
import 'package:fluttercrypto/home_page.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
void main() async {
List currencies = await getCurrency();
print(currencies);
runApp(MyApp(currencies));
}
class MyApp extends StatelessWidget {
final List _currencies;
MyApp(this._currencies); // This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red,
),
home: HomePage(_currencies),
);
}
}
Future<List> getCurrency() async {
String cryptoUrl =
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids";
http.Response response = await http.get(Uri.parse(cryptoUrl));
return jsonDecode(response.body);
}
'''
**homepage.dart**
'''import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
final List currencies;
HomePage(this.currencies);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List currencies;
final List<MaterialColor> _colors = [Colors.blue, Colors.indigo, Colors.red];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Crypto Tracker"),
),
body: cryptoWidget(),
);
}
Widget cryptoWidget() {
return Container(
child: Column(
children: [
Flexible(
child: ListView.builder(
itemCount: widget.currencies.length,
itemBuilder: (BuildContext context, int index) {
final Map currency = widget.currencies[index];
final MaterialColor color = _colors[index % _colors.length];
return _getListItemUi(currency, color);
},
),
),
],
),
);
}
ListTile _getListItemUi(Map currency, MaterialColor color) {
return ListTile(
leading: CircleAvatar(
backgroundColor: color,
child: Text(currency['name'][0]),
),
title: Text(
currency['name'],
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: _getSubtitleText(
currency['current_price'], currency['price_change_24h']),
isThreeLine: true,
);
}
Widget _getSubtitleText(int priceUSD, String percentageChange) {
TextSpan priceTextWidget = new TextSpan(
text: "\$$priceUSD\n", style: TextStyle(color: Colors.black));
String percentageChangeText = "24 hour : $percentageChange%";
TextSpan percentageChangeTextWidget;
if (double.parse(percentageChange) > 0) {
percentageChangeTextWidget = TextSpan(
text: percentageChangeText,
style: TextStyle(color: Colors.green),
);
} else {
percentageChangeTextWidget = TextSpan(
text: percentageChangeText,
style: TextStyle(color: Colors.red),
);
}
return RichText(
text: TextSpan(children: [priceTextWidget, percentageChangeTextWidget]),
);
}
}'''
**ERROR**
'''
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'double' is not a subtype of type 'String'
When the exception was thrown, this was the stack:
#0 _HomePageState._getListItemUi (package:fluttercrypto/home_page.dart:54:46)
#1 _HomePageState.cryptoWidget.<anonymous closure> (package:fluttercrypto/home_page.dart:34:24)
#2 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22)
#3 SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1201:28)
#4 SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1214:55)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building:
type 'double' is not a subtype of type 'String'
When the exception was thrown, this was the stack:
#0 _HomePageState._getListItemUi (package:fluttercrypto/home_page.dart:54:46)
#1 _HomePageState.cryptoWidget.<anonymous closure> (package:fluttercrypto/home_page.dart:34:24)
#2 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22)
#3 SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1201:28)
#4 SliverMultiBoxAdaptorElement.performRebuild.processElement `enter code here`(package:flutter/src/widgets/sliver.dart:1145:67)
====================================================================================================
'''
It's probably because currency['price_change_24h'] isn't a string. When you pass it into _getSubtitleText do currency['price_change_24h'].toString().

trying to make json request from worldtime api flutter

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

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

Update AppBar title from body widget in Scaffold

I am starting to use flutter and doing the 'Startup Name Generator' tutorial, also modifying the code to do some different things, and have come across an issue I can't solve. I want the AppBar title to show the size of the _suggestions array, but can't get it to work, have tried many different things but to no avail, always getting the exception of trying to use 'setState()' while already in a build.
This is what I currently have:
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
home: RandomWords(),
);
}
}
class RandomWordsState extends State<RandomWords> {
static final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
ValueNotifier<String> appBarTitleNotifier = ValueNotifier('Startup Name Generator: 0');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(title: ValueListenableBuilder<String>(
valueListenable: appBarTitleNotifier,
builder: (context,value,child) {
return Text(value);
}
)),
body: _buildSuggestions(),
);
}
Widget _buildSuggestions() {
var blder = ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: /*1*/ (context, i) {
if (i.isOdd) return Divider(); /*2*/
final index = i ~/2; /*3*/
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10)); /*4*/
/**** THIS NEXT LINE CAUSES THE ISSUE ****/
appBarTitleNotifier.value = 'Startup Name Generator: ' + _suggestions.length.toString();
}
return _buildRow(_suggestions[index],index);
},
);
return blder;
}
Widget _buildRow(WordPair pair, int i) {
return ListTile(
title: Text(
pair.asPascalCase + ': ' + i.toString(),
style: _biggerFont,
),
);
}
}
class RandomWords extends StatefulWidget {
#override
RandomWordsState createState() => RandomWordsState();
}
I have used a ValueNotifier and listener after doing some research into events, but same exception as when I manually used a setState() call within the ListView itemBuilder (where the issue seems to lie; calling/updating the AppBar title from within the ListView itemBuilder).
I haven't found a solution here so I am asking. Sorry if this has already been answered, but I could not find the solution.
How about using GestureDetector.
onVerticalDragEnd event not executed. but onVerticalDragDown works.
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
toolbarHeight: 100.0,
),
body: const Center(
child: RandomWords(),
),
),
);
}
}
class RandomWords extends StatefulWidget {
const RandomWords({Key? key}) : super(key: key);
#override
State<RandomWords> createState() => _RandomWordsState();
}
class _RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
String title = "Startup Name Generator";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: GestureDetector(
onTap: () {
print('tap');
},
onVerticalDragDown : (details) {
print('onVerticalDragDown');
setState(() {
title = "Startup Name Generator ("+_suggestions.length.toString()+")";
});
},
onVerticalDragEnd : (details) {
print('onVerticalDragEnd ');
setState(() {
title = "Startup Name Generator ("+_suggestions.length.toString()+")";
});
},
child:
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Icon(
// Icons.lightbulb_outline,
// color: Colors.yellow.shade600,
// size: 60,
// ),
// ),
ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if(i.isOdd) return const Divider();
final index = i ~/ 2;
if(index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return ListTile(
title: Text(
// index.toString() + ":" + _suggestions[index].asPascalCase,
_suggestions[index].asPascalCase,
style: _biggerFont,
),
);
},
),
)
);
}
}