Flutter Unable catch Exception using tryCatch - flutter

I can't catch the exception. Has anyone known how to catch it?
This is where is the error is been throwing. I just wrapped it with a try-catch block but it's not helping me, its cant catch it and I don't know what it's a cant catch
This method is coming from my custom BaseDB abstract class and this method is overridden on my custom FirebaseDBService class.
#override
Stream<Oyuncu> oyuncuStream(String UID) {
try {
return usersColRef
.doc(UID)
.withConverter<Oyuncu>(
fromFirestore: (snapshot, _) => Oyuncu.fromJson(snapshot.data()!),
toFirestore: (Oyuncu model, _) => model.toJson(),
)
.snapshots()
.map((event) {
// if (event.data() is Map<String, dynamic>) {
// var jsonDoc = event.data() as Map<String, dynamic>;
// return Oyuncu.fromJson(jsonDoc);
if(event.data() is Oyuncu) {
return event.data() as Oyuncu;
}else{
throw Exception('Unable get user from DB');
}
});
} on Exception catch (e) {
print("Test "+e.toString());
rethrow;
}
}
My debug console:
W/ProviderInstaller(16484): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
E/flutter (16484): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Exception: Unable get user from DB
E/flutter (16484): #0 FirestoreDBService.oyuncuStream.<anonymous closure> (package:p763_quiz/data/service/db/firestoreDBService.dart:41:11)
E/flutter (16484): #1 _MapStream._handleData (dart:async/stream_pipe.dart:213:31)
E/flutter (16484): #2 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #3 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #4 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (16484): #8 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (16484): #9 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter (16484): #10 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #11 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #12 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #13 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #14 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #15 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (16484): #16 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (16484): #17 _MapStream._handleData (dart:async/stream_pipe.dart:218:10)
E/flutter (16484): #18 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (16484): #19 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (16484): #20 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (16484): #21 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (16484): #22 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (16484): #23 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter (16484): #24 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter (16484): #25 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter (16484): #26 _rootRun (dart:async/zone.dart:1346:47)
E/flutter (16484): #27 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (16484): #28 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (16484): #29 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (16484): #30 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (16484): #31 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (16484): #32 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (16484): #33 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (16484): #34 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (16484): #35 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (16484):
W/IInputConnectionWrapper(16484): getExtractedText on inactive InputConnection
W/IInputConnectionWrapper(16484): getTextBeforeCursor on inactive InputConnection
W/oidim.p763_qui(16484): Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, linking, allowed)

The problem might be the keyword 'rethrow'. Because if you add this keyword, you will send the exceptions caught by oyuncuStream to the function where oyuncuStream was called.
--> oyuncuStream should also be wrapped with try-cat where it is called.

Successfully handled the error with the onError option.
#override
Stream<Oyuncu> oyuncuStream(String UID) {
return usersColRef
.doc(UID)
.withConverter<Oyuncu>(
fromFirestore: (snapshot, _) => Oyuncu.fromJson(snapshot.data()!),
toFirestore: (Oyuncu model, _) => model.toJson(),
)
.snapshots()
.map((event) => event.data() as Oyuncu).handleError((x){
throw 'There is a problem with your account';
});
}
I can get it from the caller.
void startListeningOyuncu(String id) {
oyuncuDBSubs = db.oyuncuStream(id).listen((oyuncu) {
emit(AuthState.auhtenticated(oyuncu));
})
..onError((x) {
toastBase.toastService.showToast(text: x.toString());
add(AuthEvent.logOut());
});
}
I think we cant use try-catch with the Streams,please inform me if I m wrong.

Related

flutter showing Unhandled Exception: FormatException: Filter error, bad data error

when I am trying to make an HTTP request in flutter I am receiving these errors on a particular API and I am unable to figure out what it means and how to resolve this error is it API is working properly in postman and browser
> E/flutter (15337): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FormatException: Filter error, bad data
E/flutter (15337): #0 _FilterImpl.processed (dart:io-patch/filter_patch.dart:11:32)
E/flutter (15337): #1 _FilterSink.addSlice (dart:io/data_transformer.dart:537:29)
E/flutter (15337): #2 _FilterSink.add (dart:io/data_transformer.dart:521:5)
E/flutter (15337): #3 _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:72:18)
E/flutter (15337): #4 _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:111:24)
E/flutter (15337): #5 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #6 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #7 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #8 CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
E/flutter (15337): #9 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #10 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #11 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (15337): #13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (15337): #14 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:123:11)
E/flutter (15337): #15 _HandleErrorStream._handleData (dart:async/stream_pipe.dart:256:10)
E/flutter (15337): #16 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:153:13)
E/flutter (15337): #17 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (15337): #18 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (15337): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (15337): #20 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (15337): #21 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter (15337): #22 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter (15337): #23 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter (15337): #24 _rootRun (dart:async/zone.dart:1346:47)
E/flutter (15337): #25 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (15337): #26 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (15337): #27 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (15337): #28 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (15337): #29 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (15337): #30 _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter (15337): #31 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter (15337): #32 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter (15337): #33 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter (15337):
I have tried adding other API which is am using in my application and code is working properly but for it is giving above exception and stops after HTTP call.
Future<Null> getNewHomeData() async {
setState(() {
loading = true;
});
final response = await http.get(Uri.parse(Uri.encodeFull(APIs.url_HomePage)));
print(response.statusCode);
print(response.body);
try {
print(response.body);
if(response.statusCode == 200){
final home = homeNewFromJson(response.body);
homeBanner = home.advImg;
homeContent = home.infoText;
shopCat = home.shopCat;
storeImg = home.storeImg;
topSellings = home.topSellings;
modularFurniture = home.modularFurniture;
decorFurniture = home.decorFurniture;
banner1 = home.banner1;
banner2 = home.banner2;
banner3 = home.banner3;
banner4 = home.banner4;
banner5 = home.banner5;
}
} on Exception catch (e) {
print(e);
}

type '() => Future<List<Food>>' is not a subtype of type <List<Food>

I am new to flutter. when I run my code , I got the error
E/flutter (16181): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Unhandled error type '() => Future<List<Food>>' is not a subtype of type 'List<Food>' occurred in Instance of 'MenuBloc'.
E/flutter (16181): #0 MenuBloc.mapEventToState (package:restuarant_app/Bloc/menue_bloc/menu_bloc.dart:30:7)
E/flutter (16181): <asynchronous suspension>
E/flutter (16181): #1 Bloc._bindEventsToStates.<anonymous closure> (package:bloc/src/bloc.dart:232:20)
E/flutter (16181): #2 Stream.asyncExpand.onListen.<anonymous closure> (dart:async/stream.dart:579:30)
E/flutter (16181): #3 _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter (16181): #4 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (16181): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (16181): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (16181): #7 _DelayedData.perform (dart:async/stream_impl.dart:594:14)
E/flutter (16181): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:710:11)
E/flutter (16181): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:670:7)
E/flutter (16181): #10 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (16181): #11 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16181): #12 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (16181): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (16181): #14 _rootRun (dart:async/zone.dart:1184:13)
E/flutter (16181): #15 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (16181): #16 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (16181): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (16181): #18 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (16181): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (16181):
E/flutter (16181): #0 Cubit.onError.<anonymous closure> (package:bloc/src/cubit.dart:140:7)
E/flutter (16181): #1 Cubit.onError (package:bloc/src/cubit.dart:141:6)
E/flutter (16181): #2 Bloc.onError (package:bloc/src/bloc.dart:113:11)
E/flutter (16181): #3 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #4 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #5 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #6 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #7 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #8 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:275:7)
E/flutter (16181): #9 _SyncBroadcastStreamController._sendError.<anonymous closure> (dart:async/broadcast_stream_controller.dart:393:20)
E/flutter (16181): #10 _BroadcastStreamController._forEachListener (dart:async/broadcast_stream_controller.dart:327:15)
E/flutter (16181): #11 _SyncBroadcastStreamController._sendError (dart:async/broadcast_stream_controller.dart:392:5)
E/flutter (16181): #12 _BroadcastStreamController._addError (dart:async/broadcast_stream_controller.dart:294:5)
E/flutter (16181): #13 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #14 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #15 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #16 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #17 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #18 _BufferingStreamSubscription._addError (dart:async/stream_impl.dart:275:7)
E/flutter (16181): #19 _ForwardingStreamSubscription._addError (dart:async/stream_pipe.dart:139:11)
E/flutter (16181): #20 _ForwardingStream._handleError (dart:async/stream_pipe.dart:104:10)
E/flutter (16181): #21 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:170:13)
E/flutter (16181): #22 _rootRunBinary (dart:async/zone.dart:1204:38)
E/flutter (16181): #23 _CustomZone.runBinary (dart:async/zone.dart:1093:19)
E/flutter (16181): #24 _CustomZone.runBinaryGuarded (dart:async/zone.dart:995:7)
E/flutter (16181): #25 _BufferingStreamSubscription._sendError.sendError (dart:async/stream_impl.dart:358:15)
E/flutter (16181): #26 _BufferingStreamSubscription._sendError (dart:async/stream_impl.dart:376:16)
E/flutter (16181): #27 _DelayedError.perform (dart:async/stream_impl.dart:605:14)
E/flutter (16181): #28 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:710:11)
E/flutter (16181): #29 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:670:7)
E/flutter (16181): #30 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (16181): #31 _C
I would like to get data from remote server.I use bloc library in my code.
This is part of menue_bloc.dart .I got error on line allFood= await _foodRepositiry.getAllFood() ;.
class MenuBloc extends Bloc<FoodEvent, MenuState> {
final _foodRepositiry = FoodRepository();
Map<String, List<Food>> mapFoodList;
MenuBloc({this.mapFoodList=const{}}) : super(InitialMenuState());
#override
// TODO: implement initialState
MenuState get initialState => InitialMenuState();
#override
Stream<MenuState> mapEventToState(FoodEvent event) async* {
print("loading....");
yield Loading();
if (event is GetAllFoodEvent) {
print("Get all food....");
this.mapFoodList = {};
List<Food> allFood;
allFood= await _foodRepositiry.getAllFood() ;
try {
print("in menu bloc...... ");
allFood.forEach((food) {
print(food.toString());
if (!this.mapFoodList.containsKey(food.category)) {
this.mapFoodList[food.category.toString()] = [];
}
this.mapFoodList[food.category].add(food);
});
yield Loaded(mapFoodList: this.mapFoodList);
} catch (e, stacktrace) {
print(e.toString());
print(stacktrace.toString());
When I change List<Food> allFood;to Future<List<Food>> allFood; it gives me following error
I/flutter (16181): type '() => Future<List<Food>>' is not a subtype of type 'Future<List<Food>>'
This FoodRepository code.
class FoodRepository{
final foodDao=new FoodDao();
final foodApiClient =new FoodApiClient();
Future getAllFood() async{
if(await checkInternetConnection()) {
print("fetch data from remote server");
return foodApiClient.fetchAllFood;
}else{
print("from db");
return foodDao.getAllFood();
}
}
}
This is FoodApiClient code:
class FoodApiClient{
static const baseUrl = '10.0.2.2';
final http.Client httpClient;
FoodApiClient({this.httpClient});
Future<List<Food>> fetchAllFood()async{
String url=":8080/resturant/food/allFood";
// print(url);
List<Food> foodList;
print(url);
final allFoodResponse=await httpClient.get(baseUrl+url);
print(allFoodResponse);
if (allFoodResponse.statusCode != 200) {
throw Exception('An error occured while loading food list!!! status code: '+allFoodResponse.statusCode.toString());
}
print("foodJson");
List foodJson = json.decode(allFoodResponse.body);
print(foodJson);
//foodJson.forEach((food) {foodList.add(Food.fromJson(food)); });
foodList=foodJson.map((f)=>Food.fromJson(f)).toList();
return foodList;
}
}
Future getAllFood() async{
needs to be
Future<List<Food>> getAllFood() async {
and then you need to follow the compiler errors from there, because there are a lot more instances that I cannot all name and describe here.
I strongly advise you to use proper dart formatting, and the package pedantic to tell you all about your code and how to improve it if you cannot find those places yourself.

Not able to login with a Google email in Flutter

I'm trying to login in Flutter and this is the error I'm getting when I try to login with a Google email:
E/flutter (26329): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
`enter code here`E/flutter (26329): Receiver: null
E/flutter (26329): Tried calling: []("email")
E/flutter (26329): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (26329): #1 DocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:29:42)
E/flutter (26329): #2 new User.fromDocument (package:buddiesgram/models/user.dart:23:17)
E/flutter (26329): #3 _HomePageState.saveUserInfoFirestore (package:buddiesgram/pages/HomePage.dart:83:26)
E/flutter (26329): <asynchronous suspension>
E/flutter (26329): #4 _HomePageState.controlSignIn (package:buddiesgram/pages/HomePage.dart:54:13)
E/flutter (26329): #5 _HomePageState.initState.<anonymous closure> (package:buddiesgram/pages/HomePage.dart:40:9)
E/flutter (26329): #6 _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter (26329): #7 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (26329): #8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (26329): #9 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:339:11)
E/flutter (26329): #10 _DelayedData.perform (dart:async/stream_impl.dart:594:14)
E/flutter (26329): #11 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:710:11)
E/flutter (26329): #12 _PendingEvents.schedule.<anonymous closure> *emphasized text*(dart:async/stream_impl.dart:670:7)
E/flutter (26329): #13 _rootRun (dart:async/zone.dart:1180:38)
E/flutter (26329): #14 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (26329): #15 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (26329): #16 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)`**`*enter code here*`**`
E/flutter (26329): #17 _rootRun (dart:async/zone.dart:1184:13)
E/flutter (26329): #18 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (26329): #19 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (26329): #20 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (26329): #21 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (26329): #22 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (26329):
What am I missing?
Please include a code snippet of what you are trying to do
In my understanding of your stackTrace you are trying to call list on a null object like this:
final UserData userData = someObjectHere;
function login(UserData userData){
//The problem is that userData might be null which causes your issue
String email = userData[]("Email");
}
You're solution might be to use null aware operators or to manually check whether the object you're calling a method on is not null.
String email = userData?.[]("Email");
or
if(userData != null) String email = userData?.[]("Email");

Unhandled Exception: RangeError (index): Index out of range: index should be less than

I am having a problem when trying to save a pdf using the "pdf_dart" library.
I assume the problem is linked to the image I'm downloading from the internet to try to attach to the pdf but I'm not sure what it is.
CODE
import 'dart:io';
import 'package:app_formulario/models/Customer.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart' as pdfDart;
import 'package:pdf/widgets.dart';
import 'package:image/image.dart' as imageDart;
import 'package:flutter/material.dart' as materialDart;
import 'package:http/http.dart' as http;
class PDFBloc {
PDFBloc() {
final Document pdf = Document();
http
.get(
"https://clsp.com.br/wp-content/uploads/2018/05/logo-clsp-500px.png")
.then((onValue) {
final image = pdfDart.PdfImage(
pdf.document,
image: onValue.bodyBytes,
width: 300,
height: 150,
);
pdf.addPage(Page(build: (Context context) {
return Center(
child: Image(image),
); // Center
}));
criarPDF(pdf);
});
}
void criarPDF(Document pdf) async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
appDocPath = "/storage/emulated/0/Android/data/com.rwrd.app_formulario";
final File file = File('$appDocPath/example.pdf');
file.writeAsBytesSync(pdf.save());
}
The error happens right when I am going to save the pdf with the image, that is, apparently the image is downloaded normally, however when inserting it in the pdf and trying to save it, the error is caused.
I don't know if the way I'm saving is the correct one, maybe that's it, but unfortunately I can't access the file folder without going all the way through it.
The error stack
E/flutter (18670): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: RangeError (index): Index out of range: index should be less than 6307: 6308
E/flutter (18670): #0 Uint8List.[] (dart:typed_data-patch/typed_data_patch.dart:2209:7)
E/flutter (18670): #1 PdfImage._prepare
package:pdf/src/image.dart:183
E/flutter (18670): #2 PdfObject._write
package:pdf/src/object.dart:53
E/flutter (18670): #3 PdfOutput.write
package:pdf/src/output.dart:69
E/flutter (18670): #4 SetMixin.forEach (dart:collection/set.dart:148:30)
E/flutter (18670): #5 PdfDocument._write
package:pdf/src/document.dart:168
E/flutter (18670): #6 PdfDocument.save
package:pdf/src/document.dart:176
E/flutter (18670): #7 Document.save
package:pdf/widgets/document.dart:71
E/flutter (18670): #8 PDFBloc.criarPDF
package:app_formulario/blocs/pdfBloc.dart:53
E/flutter (18670): <asynchronous suspension>
E/flutter (18670): #9 new PDFBloc.<anonymous closure>
package:app_formulario/blocs/pdfBloc.dart:35
E/flutter (18670): #10 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (18670): #11 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (18670): #12 _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
E/flutter (18670): #13 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
E/flutter (18670): #14 Future._propagateToListeners (dart:async/future_impl.dart:709:32)
E/flutter (18670): #15 Future._completeWithValue (dart:async/future_impl.dart:524:5)
E/flutter (18670): #16 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:32:15)
E/flutter (18670): #17 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:290:13)
E/flutter (18670): #18 _withClient (package:http/http.dart)
E/flutter (18670): <asynchronous suspension>
E/flutter (18670): #19 get
package:http/http.dart:46
E/flutter (18670): #20 new PDFBloc
package:app_formulario/blocs/pdfBloc.dart:18
E/flutter (18670): #21 FormBloc._recoverCustomerInformations
package:app_formulario/blocs/formBloc.dart:37
E/flutter (18670): #22 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (18670): #23 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (18670): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (18670): #25 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
E/flutter (18670): #26 _DelayedData.perform (dart:async/stream_impl.dart:593:14)
E/flutter (18670): #27 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:709:11)
E/flutter (18670): #28 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:669:7)
E/flutter (18670): #29 _rootRun (dart:async/zone.dart:1122:38)
E/flutter (18670): #30 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (18670): #31 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (18670): #32 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (18670): #33 _rootRun (dart:async/zone.dart:1126:13)
E/flutter (18670): #34 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (18670): #35 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (18670): #36 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (18670): #37 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (18670): #38 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (18670):
change pdf image widget to this,
final image = pdfDart.PdfImage.jpeg(
pdf.document,
image: onValue.bodyBytes,
);
now, your image should appear in the pdf but you will have to resize your image if you want to fix height and width.

How to handle dispatch after object dispose in flutter_bloc package?

I am using flutter_bloc & bloc package to manage state.
In child page i am initialize bloc & while back parent page dispose the bloc object.
When i comes back immediately on parent page that time bloc throw error Unhandled Exception: Bad state: Cannot add new events after calling close because on child page on load i am calling api in bloc. which trigger state after completed api. At that time already bloc object disposed.
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: Cannot add new events after calling close
E/flutter (17290): #0 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:249:24)
E/flutter (17290): #1 Subject._add (package:rxdart/src/subjects/subject.dart:124:16)
E/flutter (17290): #2 Subject.add (package:rxdart/src/subjects/subject.dart:118:5)
E/flutter (17290): #3 Bloc._bindStateSubject.<anonymous closure> (package:bloc/src/bloc.dart:90:23)
E/flutter (17290): #4 Stream.forEach.<anonymous closure>.<anonymous closure> (dart:async/stream.dart:814:45)
E/flutter (17290): #5 _runUserCode (dart:async/stream_pipe.dart:11:23)
E/flutter (17290): #6 Stream.forEach.<anonymous closure> (dart:async/stream.dart:814:11)
E/flutter (17290): #7 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (17290): #8 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (17290): #9 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (17290): #10 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
E/flutter (17290): #11 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
E/flutter (17290): #12 _SyncBroadcastStreamController._sendData (dart:async/broadcast_stream_controller.dart:375:20)
E/flutter (17290): #13 _BroadcastStreamController._add (dart:async/broadcast_stream_controller.dart:287:5)
E/flutter (17290): #14 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (17290): #15 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (17290): #16 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (17290): #17 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
E/flutter (17290): #18 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
E/flutter (17290): #19 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:132:11)
E/flutter (17290): #20 _ForwardingStream._handleData (dart:async/stream_pipe.dart:98:10)
E/flutter (17290): #21 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:164:13)
E/flutter (17290): #22 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (17290): #23 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (17290): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (17290): #25 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
E/flutter (17290): #26 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter (17290): #27 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:707:11)
E/flutter (17290): #28 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:667:7)
E/flutter (17290): #29 _rootRun (dart:async/zone.dart:1120:38)
E/flutter (17290): #30 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (17290): #31 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (17290): #32 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter (17290): #33 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (17290): #34 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (17290): #35 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (17290): #36 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter (17290): #37 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (17290): #38 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
So how handle these when bloc already disposed ?
Use common bloc for parent and child.
Create/Initialise bloc in parent when calling child do as following:
`BlocProvider.value( value: BlocProvider.of<BlocA>(context), child: ScreenA(), );`
By writing above you will keep alive the bloc from dispose,
Then you can simply access bloc in child as following:
BlocProvider.of<BlocA>(context)
Just don't dispose it in child,
And then, when you go back to parent from child your bloc won't get disposed and it will only dispose when parent destroy or dispose.
Everything is written there in readme:
https://pub.dev/packages/flutter_bloc