I'm screenshotting one widget and have it as Uint8List.
Path provider and Share Plus doesn't support sharing files on web. Is anyone manage to share image as Uint8List from web?
Not sure if we could share the image but we can download an image with uint8List. Try the following
In index.html add this script
<script src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>
Use this in flutter
import 'dart:html' as html; //ignore: avoid_web_libraries_in_flutter
import 'dart:js' as js;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({
Key ? key
}): super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key ? key
}): super(key: key);
#override
State < MyHomePage > createState() => _MyHomePageState();
}
class _MyHomePageState extends State < MyHomePage > {
final ImagePicker _picker = ImagePicker();
XFile ? image;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
onTap: () async {
image = await _picker.pickImage(source: ImageSource.gallery);
},
child: const Icon(
Icons.upload,
color: Colors.black,
),
),
const SizedBox(
height: 50,
),
TextButton(
onPressed: () async {
// Directory tempDir = await getTemporaryDirectory();
// String tempPath = tempDir.path;
// print(tempPath);
saveImg(await image!.readAsBytes(), "downloadImg.png");
},
child: const Text("SHARE"))
],
),
),
),
);
}
void saveImg(Uint8List bytes, String fileName) =>
js.context.callMethod("saveAs", [
html.Blob([bytes]),
fileName
]);
}
Related
I am currently creating a PDF to display inputted data from the user and I want to display the pdf in a new tab so they can either print it or download it or just close out.
The current PDF creation method is:
Future<void> createPDF() async{
final PdfDocument document = PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 20),
brush: PdfSolidBrush(PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, '$NewConfig.pdf');
}
then to open the file I have this method:
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
PdfView(controller: pdfController);
}
The issue I am running into is the new tab that opens displays this:
37806870454946551310371311462502541310493248321119810613106060131047841211121013247679711697108111103131047809710310111532503248328213106262131010111010011198106131050324832111981061310606013104784121112101324780971031011151310477510510011532915132483282931310476711111711011632491310478210111511111711499101115326060626213101310477710110010597661111203291483248325357533256525093131062621310101110100111981061310513248321119810613106060131047671111171101163249131047841211121013247809710310111513104775105100115329152324832829313104780971141011101163250324832821310626213101011101001119810613105232483211198106131060601310478412111210132478097103101131047809711410111011632513248328213104767111110116101110116115329153324832823254324832823255324832829313104782101115111117114991011153260601310478011411199831011163291478068703247841011201169313104770111110116326060131047994998565353545345534851514552101565345985399504553565154485748981015048513256324832821310626213101310626213101310626213101011101001119810613105332483211198106131060601310477010510811610111432477010897116101681019911110010113104776101110103116104325713106262131011511611410197109131012094434001140114131010111010011511611410197109131010111010011198106131054324832111981061310606013104770105108116101114324770108971161016810199111100101131047761011101031161043257131062621310115116114101971091310120941140082082131010111010011511611410197109131010111010011198106131055324832111981061310606013104770105108116101114324770108971161016810199111100101131047761011101031161043250505713106262131011511611410197109131012094101143657534916133239129252135241322146718217921720554949169175213642071871051869320038539138254122147698014597301321532472302034337215176592471105216061243225561856225136314915325146710778105157252165162164620485841822824418812023711612918515227228989410517881108111961551426748148156415712843203422444621814625525521417525223914411496171408922315518373155231199452369425460117164423832424364215131201621976962111762147219361615719178233240147195177114221341688311317017616894244613148201231158207322789229127168204178122502141225624896143871835514860100184613795972178011310101110100115116114101971091310101110100111981061310563248321119810613106060131047841211121013247701111101161310478311798116121112101324784121112101491310476697115101701111101163247721011081181011161059997131047691109911110010511010332478710511065110115105691109911110010511010313106262131010111010011198106131012011410110213104832571310484848484848484848483254535351533210213104848484848484848495532484848484832110131048484848484848485550324848484848321101310484848484848484956483248484848483211013104848484848484850535732484848484832110131048484848484848525256324848484848321101310484848484848485351543248484848483211013104848484848484854505232484848484832110131048484848484848575152324848484848321101310116114971051081011141310606013104782111111116324932483282131047831051221013257131062621310131011511697114116120114101102131049485157131037376979701310
which I am guessing is the bytes but am at a loss as to what I am supposed to do from here.
any info?
I suggest you to directly use a pub package like native_pdf_view.
Its easyer than your method in my opinion and you dont need to reinvente the wheel.
EDIT:
Here is a code that i do quickly, it can be improve with a ChangeNotifier etc... to handle Future function, But it work.
main.dart
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart' as scPdf;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late PdfController _pdfController;
bool isPdfLoaded = false;
Future<void> createPDF() async{
final scPdf.PdfDocument document = scPdf.PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', scPdf.PdfStandardFont(scPdf.PdfFontFamily.helvetica, 20),
brush: scPdf.PdfSolidBrush(scPdf.PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, 'test.pdf');
}
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
setState(() {
isPdfLoaded = true;
_pdfController = pdfController;
});
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'PDF',
),
isPdfLoaded ? Container(width : size.width, height: size.height * 0.5, child : PdfView(controller: _pdfController)) : Text("Pdf not loaded"),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: createPDF,
tooltip: 'CreatePDF',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Re-EDIT:
This is the exemple using Navigator.push to display the pdf in another page:
main.dart
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
import 'package:stackoverflow/pdf_view.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart' as scPdf;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late PdfController _pdfController;
bool isPdfLoaded = false;
Future<void> createPDF() async{
final scPdf.PdfDocument document = scPdf.PdfDocument();
document.pages.add().graphics.drawString(
'Hello World!', scPdf.PdfStandardFont(scPdf.PdfFontFamily.helvetica, 20),
brush: scPdf.PdfSolidBrush(scPdf.PdfColor(0, 0, 0)),
bounds: Rect.fromLTWH(20, 60, 150, 30));
List<int> bytes = await document.save();
document.dispose();
saveAndLaunchFile(bytes, 'test.pdf');
}
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
Uint8List test = Uint8List.fromList(bytes);
final pdfController = PdfController(document:PdfDocument.openData(test));
await Navigator.of(context).push((MaterialPageRoute(builder: (context) => PdfViewPage(pdfController: pdfController))));
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Click on Floating button to create and open your pdf in another view',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: createPDF,
tooltip: 'CreatePDF',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
pdf_view.dart
import 'package:flutter/material.dart';
import 'package:native_pdf_view/native_pdf_view.dart';
class PdfViewPage extends StatelessWidget {
const PdfViewPage({Key? key, required this.pdfController}) : super(key: key);
final PdfController pdfController;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: PdfView(controller: pdfController)
),
);
}
}
I've some trouble when I try to save the reorderable grid after I've changed it.
It seem to work good but when i open again the app is only a grey screen.I've added some snackbar that print the list before and after been saved with GetStorage but they are in the right order as you can see in this screenshot
imagePaths before being saved
imagePaths loaded from GetStorage
grey screen when I reopening the app
import 'package:flutter/material.dart';
import 'package:reorderable_grid_view/reorderable_grid_view.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
void main() async {
await GetStorage.init();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final box = GetStorage();
List<String> imagePaths = GetStorage().read('imagePaths') ?? [
'remote',
'timelapse',
'video',
'hdr',
'star',
'lightning',
'drop',
'vibrate',
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: ReorderableGridView.count(
crossAxisCount: 2,
childAspectRatio: 1,
children: imagePaths
.map((String path) => Card(
key: ValueKey(path),
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(path),
SvgPicture.asset(
'assets/$path.svg',
color: Colors.red,
),
],
),
),
))
.toList(),
onReorder: (oldIndex, newIndex) async {
String path = imagePaths.removeAt(oldIndex);
imagePaths.insert(newIndex, path);
setState(() {
Get.snackbar(
'before GetStorage:',
'${imagePaths.toString()}',
snackPosition: SnackPosition.BOTTOM,
);
box.remove('imagePaths');
box.write('imagePaths', imagePaths);
Get.snackbar(
'from GetStorage:',
'${box.read('imagePaths').toString()}',
snackPosition: SnackPosition.BOTTOM,
);
});
},
),
);
}
}
I solved your problem like here:
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List imagePaths = [
'remote',
'timelapse',
'video',
'hdr',
'star',
'lightning',
'drop',
'vibrate'
];
final box = GetStorage();
final String key = 'imagePaths';
#override
void initState() {
imagePaths = box.read(key);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ReorderableGridView.count(
crossAxisCount: 2,
childAspectRatio: 1,
children: imagePaths
.map((path) => Card(
key: ValueKey(path),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(path),
SvgPicture.asset(
'assets/$path.svg',
color: Colors.red,
),
],
),
))
.toList(),
onReorder: (oldIndex, newIndex) async {
String path = imagePaths.removeAt(oldIndex);
imagePaths.insert(newIndex, path);
setState(() {
box.remove(key);
box.write(key, imagePaths);
});
},
),
);
}
}
i want to upload a image with image_picker_web to my flutter website.
This works without problems.
Than i need to edit the image (for example grayscale or draw on it) with the image_class from pub_dev and after that i want to display it on my flutter website.
But all my attempts not working. I have problem to convert the img.image class Image back to Uint8List for displaying in Image.memory .
Can anybody help me with a little code snippet?
Ronny
This is my code:
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_web/image_picker_web.dart';
void main() {
runApp(const MyApp());
}
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(
title: 'Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Draw Picture Homepage'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late Uint8List pickedImage;
bool imageAvailable = false;
#override
void initState() {
super.initState();
}
getImageWeb() async {
final fromPicker = await ImagePickerWeb.getImageAsBytes();
/* // Fill it with a solid color (blue)
img.fill(test, img.getColor(0, 0, 255));
// Draw some text using 24pt arial font
img.drawString(test, img.arial_24, 0, 0, 'Hello World');
// Draw a line
img.drawLine(test, 0, 0, 320, 240, img.getColor(255, 0, 0), thickness: 3);
// Blur the image
img.gaussianBlur(test, 10); */
setState(() {
pickedImage = fromPicker!;
imageAvailable = true;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: 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: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () => getImageWeb(),
child: Text('Select Image'),
),
Container(
width: 300,
child: imageAvailable ? Image.memory(pickedImage) : const SizedBox(height: 10),
),
const Text('Test'
),
],
),
),
);
}
}
This works. But i am not able to convert the edited Image (which is img.Image after editing) back to Uint8List to show it on the Website.
I'm using Shared Preferences in flutter , but it not working with me in vs code and andriod studio , after adding dependencies and import the package then try the app nothing happen when clicking on the button which it do the function.
------- this my code in home page --------
import 'package:flutter/material.dart';
import 'package:flutter_application_2/another_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'another_screen.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Shared Preference',
theme: ThemeData(primarySwatch: Colors.blue),
home: const MyHomePage(title: 'Shared Preference'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
super.initState();
setData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ElevatedButton(
child: const Text('Go Another Screen'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => const AnotherScreen(),
));
},
),
),
);
}
setData() async {
SharedPreferences _pref = await SharedPreferences.getInstance();
_pref.setString('name', 'Rady');
_pref.setInt('age', 19);
_pref.setString('university', 'Rady');
_pref.setInt('height', 19);
_pref.setStringList('skills', ['Dart', 'Flutter']);
}
}
----- the second page ------
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AnotherScreen extends StatefulWidget {
const AnotherScreen({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() => AnotherScreenState();
}
class AnotherScreenState extends State<AnotherScreen> {
String _name = '';
int? _age;
String _university = '';
int? _height;
List<String> _skills = ['', ''];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Info Screen'),
),
body: DefaultTextStyle(
style: const TextStyle(
fontSize: 30, fontWeight: FontWeight.bold, color: Colors.black),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Name : $_name'),
Text('Age : $_age'),
Text('University : $_university'),
Text('Height : $_height'),
Text('Skill1 : ${_skills[0]}'),
Text('Skill2 : ${_skills[1]}'),
ElevatedButton(
child: const Text('Get Data'),
onPressed: () async {
await getData();
},
)
],
),
),
),
);
}
getData() async {
SharedPreferences _pref = await SharedPreferences.getInstance();
setState(() {
_name = _pref.getString('name')!;
_age = _pref.getInt('age');
_university = _pref.getString('university')!;
_height = _pref.getInt('height');
_skills = _pref.getStringList('skills')!;
});
}
}
Storing Data in shared preferences requires the await keyword
SharedPreferences _prefs = await SharedPreferences.getInstance();
await _prefs.setString('token', newToken);
I wanted to build a feature where a user will be typing texts then may wanted to add a file, pick an image then the picked image will now be returned at the original text screen with the texts there too. I have develop the feature for inputting the texts my text feature then i am stuck at how the picked image will be returned to that same text place. Please how can i get this feature?
First You Need to Add dependencies image_picker: ^0.6.4 Used the latest version, Second
pickup an image
class _MyHomePageState extends State<MyHomePage> {
File _iamge;
Future CameraImage() async{
var iamge =await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_iamge = iamge;
});
}
Here Is Full Code To know Better Understand.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _iamge;
Future CameraImage() async{
var iamge =await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_iamge = iamge;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Container(
height: 500,
width: double.infinity,
color: Colors.blue,
child: _iamge==null?Center(child: Text("NO Image
Select")):Image.file(_iamge),
),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(onPressed: (){
CameraImage();
},child: Icon(Icons.camera),),
SizedBox(width: 20,),
FloatingActionButton(onPressed: (){},
child: Icon(Icons.photo_library),),
],
)
],
),
);
}
}
receive.dart
import 'package:flutter/material.dart';
import 'package:flutterapp/data.dart';
import 'package:provider/provider.dart';
class ReceiveData extends StatelessWidget {
#override
Widget build(BuildContext context) {
final providerdata= Provider.of<Data>(context);
return Scaffold(
body: Center(
child:
Text(providerdata.value.toString(),style:TextStyle(fontSize:50),),
),
);
}
}