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

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

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

Why does my jsonDecode() method in Flutter throw a Format Exception?

I've been learning mobile development on Flutter for a while and currently trying to build a single-page text translation app, for exercise. I tried to integrate a Google Translate API.
I'm having trouble running the app due to an error (Format Exception) in the jsonDecode() method I use to extract the translation result json object (Post method HTTP request)
Here's my home screen code
import 'package:flutter/material.dart';
import '../models/input_model.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = TextEditingController();
final translation = Sentence();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Translation App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
////////////// Widget for the translation source text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)))),
)),
////////////////////////////////////////////////////////////////////
ElevatedButton(
onPressed: () {
Sentence.connectToAPI('en', 'de', textController.text); //static language option
setState(() {}); //input for testing
},
child: Text('Translate')),
////////////// Widget for the translation result text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: Text((translation.trans == null)
? 'no data'
: translation.trans.toString())),
],
),
),
);
}
}
And here's the model file where the problem lies:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Sentence {
Sentence({
this.trans,
this.orig,
this.backend,
});
String? trans;
String? orig;
int? backend;
factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
trans: json["trans"],
orig: json["orig"],
backend: json["backend"],
);
Map<String, dynamic> toJson() => {
"trans": trans,
"orig": orig,
"backend": backend,
};
static Future<Sentence> connectToAPI(
String from, String to, String text) async {
String pathURL =
'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
var response =
await http.post(Uri.parse(pathURL), headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'PostmanRuntime/7.29.0'
}, body: {
'sl': from,
'tl': to,
'q': text
});
var jsonObject = jsonDecode(response.body); //the exception error message pointed here
var textObject = (jsonObject as Map<String, dynamic>)['sentences'];
return Sentence.fromJson(textObject);
}
}
The exception error message was:
FormatException (FormatException: Unexpected character (at character 1)
^
I'm still a newbie and it really confuses me. I tried to search for the explanation of the error message on Google but still having a hard time understanding it. What seems to be the problem here?

How to convert a string to a blob using universal_html plugin in Flutter web

I am trying to show a Google Drive file using Flutter web app. At this stage the best I can do is open a pdf url in browser. I am able to get a blob string from a Google Drive file using Google Apps Script in Flutter web but when I am using universal_html plugin to open pdf, I can't convert string to blob object and Flutter project throws an error in console as below when showing blob.
Problem:
How to convert blob string from Google Apps script to Blob object that can be used in html.Url.createObjectUrlFromBlob(blob); ?
Step1: Set up Google Apps Script project.
function doGet(){
var blobText = getFileAsBlob("1wzR-7fWT_vA7jVSUnDwSj28j82scazkkup8Ovr9kwjv");
return ContentService.createTextOutput(blobText).setMimeType(ContentService.MimeType.JSON);
//return HtmlService.createHtmlOutput(blobText);
}
//Return file as blob by Id
function getFileAsBlob(fileId) {
var file = DriveApp.getFileById(fileId);
var blob = file.getBlob().getDataAsString();
return blob;
}
Step2: Set up Flutter project. Add dependency in pubspec.yaml
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart' as html;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PDF viewer demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Show Google Drive file in Flutter'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String path;
Future<String> _getFileFromGoogleDrive() async {
final driveUrl =
"https://script.google.com/macros/s/AKfycbzY-XQxMfq6KeeRL_-4y8DnnBanu3PX813Ipfz8xogD7dgQKb2Y/exec";
return await http.get(driveUrl).then((response) {
print(response.body); //Error
//TODO:
html.Blob blob = new html.BlobText(response.body);
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, "_blank");
html.Url.revokeObjectUrl(url);
return null;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Click to open file."),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _getFileFromGoogleDrive,
tooltip: 'Show file',
child: Icon(Icons.file_present),
),
);
}
}
Error: Flutter error when pressing Show file button:
Bad UTF-8 encoding found while decoding string: %PDF-1.5
%����
2 0 obj
<< /Linearized 1 /L 17762 /H [ 750 126 ] /O 6 /E 17487 /N 1 /T 17486 >>
endobj
3 0 obj
<< /Type /XRef /Length 51 /Filter /FlateDecode /DecodeParms << /Columns 4 /Predictor 12 >> /W [ 1 2 1 ] /Index [ 2 24 ] /Info 11 0 R /Root 4 0 R /Size 26 /Prev 17487 /ID [<439e80749f258bfcf6a670df0083ad46><439e80749f258bfcf6a670df0083ad46>] >>
stream
x�cbd�g`b`8 $���XF#��Dh ! af�Me`b<p����b

convert data from a csv to a dynamic List (Flutter)

I create an app that loads the CSV file and displays it as a list view, I have used the following example. https://gist.github.com/Rahiche/9b4b2d3b5c24dddbbe662b58c5a2dcd2
The problem is that my List, don't generate rows
I/flutter ( 2158): [[M01, Plastics, 50, NA
I/flutter ( 2158): M02, Plastics, 85, NA
I/flutter ( 2158): M03, Wood, 50, NA
I/flutter ( 2158): M04, Wood, 15, 3
I/flutter ( 2158): M05, Plastics, 50, NA]]
Here is my code
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
and my ford.csv
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
---
i tried the hints from https://pub.dev/packages/csv#-readme-tab- and from
Not viewing Table Layout from a csv in flutter and I have read several csv files
but every time i have the same issues.
what am I doing wrong??
Please help a new flutter developer. ;)
You can copy paste run full code below
I add setState in function loadAsset()
I did not encounter column width issue, if you still have this issue, please try to add column 2 , 3 or shrink width of FixedColumnWidth
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(100.0),
2: FixedColumnWidth(50.0),
},
code snippet
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
working demo
animated gif did not show correct green color,
so I paste final result in second picture
full code
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
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: TableLayout(),
);
}
}
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
It's because of different EOL (END OF LINE) characters that are used to terminate a line in file. i.e Some program use '\r\n' while other '\n'.
So to solve the issue you have to consider that. i.e I am using csv package on window os and while reading from a csv file, you should specify eol argument to convert method of the CsvToListConverter().
return CsvToListConverter().convert(csv.data, eol: '\n');
The fast_csv parser is for parsing CSV data.
It is 2.9-4.7 times faster than the csv parser.
If you need to parse large amounts of data, then it will be more efficient.
Line endings are \n, \r\n or \r (no need to configure).
import 'package:fast_csv/fast_csv.dart' as _fast_csv;
void main(List<String> args) {
final res = _fast_csv.parse(_csv);
print(res);
}
final _csv = '''
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
''';
Output:
[[M01, Plastics, 50, NA], [M02, Plastics, 85, NA], [M03, Wood, 50, NA], [M04, Wood, 15, 3], [M05, Plastics, 50, NA]]

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.