error in MemoryImage not defined in package pdf/widgets.dart - flutter

import 'dart:io';
import 'package:flutter/material.dart' as material ;
import 'package:flutter/services.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
class PdfParagraphApi {
static Future<void> generate(key) async {
final pdf = pw.Document();
final img = pw.MemoryImage(await rootBundle.load('assets/img.png')).buffer.asUint8List();
pdf.addPage(
pw.MultiPage(
build: (context) => <pw.Widget>[
pw.Image(img),
]),
);
}
}
i'm trying to create a pdf with an image inside it and i'm using the library pdf/widgets.dart to create the image as i found in flutters documentation but i'm facing a problem.
the error message is the following :
The function 'MemoryImage' isn't defined.
Try importing the library that defines 'MemoryImage', correcting the name to the name of an existing function, or defining a function named 'MemoryImage'.dartundefined_function
insert image into pdf not working

Replace pw.MemoryImage with material.MemoryImage, because MemoryImage comes from the painting library, which is included inside the material library.

Try to replace the below import:
import 'package:flutter/material.dart' as material ;
with this import 'package:flutter/material.dart';

Try this below way:
Imports you need
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
and in the top you need to define the image you want to print _imageFile = someImage:
Uint8List? _imageFile ;
Then this is the function to make an image to pdf and save it in the Downloads Folder
Future getPdf() async {
var random = Random();
var uniqueNum = random.nextInt(99999);
//get storage permission
Map<Permission, PermissionStatus> storagePermission = await [
Permission.storage,
].request();
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(_imageFile), fit: pw.BoxFit.contain),
);
},
),
);
String path = await ExternalPath.getExternalStoragePublicDirectory(
ExternalPath.DIRECTORY_DOWNLOADS);
String mainPath = "$path/Report$uniqueNum.pdf";
File pdfFile = File(mainPath);
pdfFile.writeAsBytesSync(await pdf.save());
}

Related

How to convert text file asset into List<String>

May I ask, How do i read a plaintext, located at assets/plaintext.txt, with the following content
1st line
2nd line
3rd line
and convert it into something, which act like, the following would have
List<String> stri = <String>[
"1st line",
"2nd line",
"3rd line",
];
The following code makes the app screen go black
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
String stri = '0';
Future<void> main() async {
stri = await rootBundle.loadString('assets/plaintext.txt');
runApp(
const MyApp(),
);
}
Thanking you...
You can load a string first using rootBundle.loadString() method, and then construct a list out of a pattern.
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
void loadAsset() async {
String loadedString = await rootBundle.loadString('assets/plaintext.txt');
List<String> result = loadedString.split('\n');
}
Don't forget to add it in your pubspec.yaml
flutter:
assets:
- assets/plaintext.txt

How to implement App Tracking Transparency in Flutter

I submitted my app to apple but it got rejected because i haven't added App transparency. SO far, i have imported the dependency into pubspec.yaml and i'm confused if there is more that i need to add to my main.dart in the below code, please help
import 'dart:io';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:path_provider/path_provider.dart';
import 'app.dart';
import 'models/constants.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final TrackingStatus status =
await AppTrackingTransparency.requestTrackingAuthorization();
await EasyLocalization.ensureInitialized();
await Firebase.initializeApp();
Directory directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
await Hive.openBox(Constants.bookmarkTag);
await Hive.openBox(Constants.resentSearchTag);
await Hive.openBox(Constants.notificationTag);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark));
runApp(
EasyLocalization(
supportedLocales: [Locale('en'), Locale('ar'), Locale('es')],
path: 'assets/translations',
fallbackLocale: Locale('en'),
//Defaut language
startLocale: Locale('en'),
useOnlyLangCode: true,
child: MyApp(),
)
);
}
Yes. For iOs you need to specify a key in the Info.plist.
Open file app/ios/Runner/Info.plist
and add the following line:
NSUserTrackingUsageDescription
This identifier will be used to deliver personalized ads to you.
As it is specified in the package:
https://pub.dev/packages/app_tracking_transparency

Flutter pdf file isnt saving and showing error

I am trying to simple generate and save pdf issue is its showing error in my code
I am doing like this
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
onTap: () async{
final pdf = pw.Document();
pdf.addPage(
pw.Page(
build: (pw.Context context) => pw.Center(
child: pw.Text('Hello World!'),
),
),
);
// Share.shareFiles([pdf], text: 'Reports');
final output = await getTemporaryDirectory();
final path = "${output.path}/temp.pdf";
final file = File(path); // here its showing error 2 positional
await file.writeAsBytes(pdf.save()); // here its showing The method 'writeAsBytes' isn't defined for the type 'File'.
},
Plugin versions
pdf: 2.1.0 & path_provider: ^2.0.2
I search every where but I didnt find any solution cant find it so why I am getting this error -_-
Use io library to write the file:
import 'dart:io' as io;
onTap: () async{
final pdf = pw.Document();
pdf.addPage(
pw.Page(
build: (pw.Context context) => pw.Center(
child: pw.Text('Hello World!'),
),
),
);
// Share.shareFiles([pdf], text: 'Reports');
//replace your code to save file from bellow
final output = await getTemporaryDirectory();
final path = "${output.path}/temp.pdf";
final file = await io.File(path).writeAsBytes(pdf.save());
},
The error would be due to methods defined in the pdf library. You can use default io library to solve that.

How to access another class from a different file in the same flutter project?

Hello everyone please i just started learning and working on flutter some few months ago,i am now trying my hands on it.
I want to know if there is a way that will enable me to access the class Position in the main.dart from the request.dart in such that the part where i add my api in the Uri.parse() the ${postion.latitude} and${position.longitude} won't be Undefined and refer to the Position class in the main.dart file. Thank you!
main.dart file
'''
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:rider_app/AllScreens/searchScreen.dart';
import 'package:rider_app/AllWidgets/Divider.dart';
import 'package:rider_app/Assistants/assistantMethods.dart';
import 'package:rider_app/DataHandler/appData.dart';
class MainScreen extends StatefulWidget
{
static const String idScreen = "mainScreen";
const MainScreen({Key key}) : super(key: key);
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen>
{
Completer<GoogleMapController> _controllerGoogleMap = Completer();
GoogleMapController newGoogleMapController;
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
Position currentPosition;
var geoLocator = Geolocator();
double bottomPaddingOfMap=0;
void locatePosition() async
{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
currentPosition= position;
LatLng latLatPosition = LatLng(position.latitude, position.longitude);
//Camera move
CameraPosition cameraPosition = new CameraPosition(target: latLatPosition, zoom: 16);
newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
//newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
String address = await AssistantMethods.searchCoordinateAddress(position, context);
}
'''
request.dart file
'''
import 'dart:convert';
import 'dart:html';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'package:rider_app/configMaps.dart';
import 'package:rider_app/lib/AllScreens/mainscreen.dart';
class RequestAssistant
{
static Future<dynamic> getRequest(url) async
{
var url = Uri.parse("https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$mapKey");
http.Response response = await http.get(url);
try
{
if(response.statusCode==200)
{
String jSonData = response.body;
var decodeData = jsonDecode(jSonData);
return decodeData;
}
else
{
return "failed";
}
}
catch(exp)
{
return "failed";
}
}
}'''
You can pass in getRequest method life
getRequest(Position position) async {...}

How to export and use global variable

I am creating a Flutter App and I need a global http client with some setup.
Flutter: 1.5.4
Dart: 2.3.2
// utils/http.dart
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
Dio http = Dio();
void main() async {
// Save cookies to cookie jar.
Directory appDir = await getApplicationDocumentsDirectory();
http.interceptors.add(CookieManager(PersistCookieJar(dir: appDir.path)));
}
// main.dart
import 'package:flutter/material.dart';
import 'app.dart';
import 'utils/http.dart';
void main() {
print(http.interceptors); // returns []
runApp(App());
}
I expect that main function in http should be automatically executed.
A common solution to this is to wrap it in a Widget and place that widget in the Widget Tree. High up in the tree, so that it's sort of global. It's called "lifing state up".
The out of box solution of Flutter for such things is InheritedWidget. It's worth looking at and understand because most 3rd-party solutions rely on it.
To make life a tad easier, however, I use pacakge:provider. Code would look like so:
Creating
Provider<Dio>(
builder: (_) => Dio(),
child: MaterialApp(/*...*/)
);
Consuming
later in the widget tree:
Consumer<Dio>(
builder: (ctx, dio, _) {
// widget builder method
debugPrint('Dio instance: ${dio}');
return Container();
}
);