Flutter Getx Providers get fired twice - flutter

I'm using the Getx package to manage my app state,
there is something wired happening,
all the providers get initialized multiple times
this is my initialization method
Future<void> main() async {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
ErrorWidget.builder = (e) => ErrorScreen(e.exception);
await App.initializeProviders();
if (Get.find<AuthProvider>().isAuth) await App.initializeUserProviders();
runApp(const Appi());
}
class Appi extends StatelessWidget {
const Appi({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container();
}
}
and these is the two methods that I use to initialise the providers
first core providers
static initializeProviders() async {
try {
Get.lazyPut<AuthProvider>(() => AuthProvider(), fenix: true);
Get.lazyPut<SettingsProvider>(() => SettingsProvider(), fenix: true);
Get.put<NotificationsProvider>(NotificationsProvider(), permanent: true);
await Get.find<AuthProvider>().load();
await Get.find<SettingsProvider>().load();
await FirebasePlugin.initializeApp();
} catch (e) {
//
print(e);
}
}
and second for the authenticated users
static initializeUserProviders() async {
try {
Get.lazyPut<MainProvider>(() => MainProvider(), fenix: true);
Get.lazyPut<FiltersProvider>(() => FiltersProvider(), fenix: true);
Get.lazyPut<CartProvider>(() => CartProvider(), fenix: true);
Get.lazyPut<SearchProvider>(() => SearchProvider(), fenix: true);
// Get.lazyPut(() => HomeProvider(), fenix: true);
// Get.find<HomeProvider>().load();
Get.find<NotificationsProvider>().load();
Get.find<FiltersProvider>().load();
Get.find<CartProvider>().load();
} catch (e) {
//
}
}
and I got this in the debugging console
[GETX] Instance "NotificationsProvider" has been created
[GETX] Instance "NotificationsProvider" has been initialized
2[GETX] Instance "AuthProvider" has been created
2[GETX] Instance "AuthProvider" has been initialized
[GETX] Instance "NotificationsProvider" has been created
[GETX] Instance "NotificationsProvider" has been initialized
[GETX] Instance "AuthProvider" has been created
[GETX] Instance "AuthProvider" has been initialized
2[GETX] Instance "SettingsProvider" has been created
2[GETX] Instance "SettingsProvider" has been initialized
[GETX] Instance "SettingsProvider" has been created
[GETX] Instance "SettingsProvider" has been initialized
2
W/FLTFireMsgService( 5927): Attempted to start a duplicate background isolate. Returning...
Note that I use exactly the same methods and the same way in another app and everything works there to find,
// auth load
Future<void> load() async {
if (_profile.value != null && _token.value != null) return;
final localStorage = await SharedPreferences.getInstance();
final lt1 = localStorage.getString('somekey1');
final lt2 = localStorage.getString('somekey2');
final lt3 = localStorage.getString('somekey3');
final localProfile = localStorage.getString('_up');
if (lt1 != null && lt2 != null && lt3 != null && localProfile != null) {
_token.value = lt1 + lt2 + lt3;
final profile = json.decode(localProfile);
_profile.value = UserModel.fromJson(profile, avatar: profile['avatar']);
update();
return;
}
}
// filters load
load() async {
await App.getData('PRD/filters.php').then((value) {
if (value != null) {
final platforms = value["brands"] as Map<String, dynamic>;
final stores = value["stores"] as Map<String, dynamic>;
setFilters(stores.values.toList(), platforms.values.toList());
}
}).catchError((e) {
throw e;
// TODO:: handle error
});
}
void setFilters(
List<dynamic> stores,
List<dynamic> platforms, {
bool local = false,
}) {
if (stores.isEmpty || platforms.isEmpty) return;
_allPlatforms.value.clear();
_allStores.value.clear();
_allPlatforms.value.add(Filter.getDefault(isPlatform: true));
_allStores.value.add(Filter.getDefault());
for (var platform in platforms) {
_allPlatforms.value.add(Filter.fromJson(platform, isPlatform: true));
}
for (var store in stores) {
_allStores.value.add(Filter.fromJson(store));
}
if (!local) {
SharedPreferences.getInstance().then((prefs) {
prefs.setString("allPlatforms", jsonEncode(platforms));
prefs.setString("allStores", jsonEncode(stores));
});
}
update();
}
// notification load
Future<void> load() async {
final result = await _database.getAll();
if (result.length == _notifications.value.length) return;
_notifications.value.clear();
_notifications.value.addAll(result
.map((e) => NotificationModel.fromJson({
'id': e['id'],
'message': e['title'],
'type': e['type'],
'type_id': e['type_id'],
'level': e['level'],
'is_new': e['is_new'],
}))
.toList());
if (_notifications.value.isNotEmpty) {
_notifications.value
.sort((a, b) => int.parse(a.id).compareTo(int.parse(b.id)));
}
update();
}
// cart load
Future<void> load() async {
try {
final items = await database.getAll();
_cartItems.clear();
for (var e in items) {
_cartItems.add(CartItem.fromJson(e));
}
update();
} catch (e) {
rethrow;
}
}

I fix this issue as following:
I create a new flutter project,
I move my lib folder to the new project.
I guess it was a bug in VSCode or something in the android folder.

Related

Unhandled Exception: Bad state: Tried to use PaginationNotifier after `dispose` was called

I have a StateNotifierProvider that calls an async function which loads some images from the internal storage and adds them to the AsyncValue data:
//Provider declaration
final paginationImagesProvider = StateNotifierProvider.autoDispose<PaginationNotifier, AsyncValue<List<Uint8List?>>>((ref) {
return PaginationNotifier(folderId: ref.watch(localStorageSelectedFolderProvider), itemsPerBatch: 100, ref: ref);
});
//Actual class with AsyncValue as State
class PaginationNotifier extends StateNotifier<AsyncValue<List<Uint8List?>>> {
final int itemsPerBatch;
final String folderId;
final Ref ref;
int _numberOfItemsInFolder = 0;
bool _alreadyFetching = false;
bool _hasMoreItems = true;
PaginationNotifier({required this.itemsPerBatch, required this.folderId, required this.ref}) : super(const AsyncValue.loading()) {
log("PaginationNotifier created with folderId: $folderId, itemsPerBatch: $itemsPerBatch");
init();
}
final List<Uint8List?> _items = [];
void init() {
if (_items.isEmpty) {
log("fetchingFirstBatch");
_fetchFirstBatch();
}
}
Future<List<Uint8List?>> _fetchNextItems() async {
List<AssetEntity> images = (await (await PhotoManager.getAssetPathList())
.firstWhere((element) => element.id == folderId)
.getAssetListRange(start: _items.length, end: _items.length + itemsPerBatch));
List<Uint8List?> newItems = [];
for (AssetEntity image in images) {
newItems.add(await image.thumbnailData);
}
return newItems;
}
void _updateData(List<Uint8List?> result) {
if (result.isEmpty) {
state = AsyncValue.data(_items);
} else {
state = AsyncValue.data(_items..addAll(result));
}
_hasMoreItems = _numberOfItemsInFolder > _items.length;
}
Future<void> _fetchFirstBatch() async {
try {
_numberOfItemsInFolder = await (await PhotoManager.getAssetPathList()).firstWhere((element) => element.id == folderId).assetCountAsync;
state = const AsyncValue.loading();
final List<Uint8List?> result = await _fetchNextItems();
_updateData(result);
} catch (e, stk) {
state = AsyncValue.error(e, stk);
}
}
Future<void> fetchNextBatch() async {
if (_alreadyFetching || !_hasMoreItems) return;
_alreadyFetching = true;
log("data updated");
state = AsyncValue.data(_items);
try {
final result = await _fetchNextItems();
_updateData(result);
} catch (e, stk) {
state = AsyncValue.error(e, stk);
log("error catched");
}
_alreadyFetching = false;
}
}
Then I use a scroll controller attached to a CustomScrollView in order to call fetchNextBatch() when the scroll position changes:
#override
void initState() {
if (!controller.hasListeners && !controller.hasClients) {
log("listener added");
controller.addListener(() {
double maxScroll = controller.position.maxScrollExtent;
double position = controller.position.pixels;
if ((position > maxScroll * 0.2 || position == 0) && ref.read(paginationImagesProvider.notifier).mounted) {
ref.read(paginationImagesProvider.notifier).fetchNextBatch();
}
});
}
super.initState();
}
The problem is that when the StateNotifierProvider is fetching more data in the async function fetchNextBatch() and I go back on the navigator (like navigator.pop()), Flutter gives me an error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: Tried to use PaginationNotifier after dispose was called.
Consider checking mounted.
I think that the async function responsible of loading data completes after I've popped the page from the Stack (which triggers a Provider dispose).
I'm probably missing something and I still haven't found a fix for this error, any help is appreciated.

I can't list database data in Flutter

I have a problem, my database has data, but I can't list this data in the application, can you see where the problem is?
Here the database query is being implemented
#override
Stream<Either<TodoFailures, List<Todo>>> watchAll() async* {
//yield left(const InsufficientPermissions());
// users/{user ID}/notes/{todo ID}
final userDoc = await firestore.userDocument();
yield* userDoc.todoCollection
.snapshots()
.map((snapshot) => right<TodoFailures, List<Todo>>(snapshot.docs
.map((doc) => TodoModel.fromFirestore(doc).toDomain()).toList()))
.handleError((e) {
if (e is FirebaseException) {
if (e.code.contains('permission-denied') || e.code.contains("PERMISSION_DENIED")) {
return left(InsufficientPermisssons());
} else {
return left(UnexpectedFailure());
}
} else {
// ? check for the unauthenticated error
// ! log.e(e.toString()); // we can log unexpected exceptions
return left(UnexpectedFailure());
}
});
}
Below is where I capture the integrated query through the BloC
#injectable
class ObserverBloc extends Bloc<ObserverEvent, ObserverState> {
final TodoRepository todoRepository;
StreamSubscription<Either<TodoFailures, List<Todo>>>? todoStreamSubscription;
ObserverBloc({required this.todoRepository}) : super(ObserverInitial()) {
on<ObserverEvent>((event, emit) async {
emit(ObserverLoading());
await todoStreamSubscription?.cancel();
todoStreamSubscription = todoRepository
.watchAll()
.listen((failureOrTodos) => add(TodosUpdatedEvent(failureOrTodos: failureOrTodos)));
});
on<TodosUpdatedEvent>((event, emit) {
event.failureOrTodos.fold((failures) => emit(ObserverFailure(todoFailure: failures)),
(todos) => emit(ObserverSuccess(todos: todos)));
});
}
#override
Future<void> close() async {
await todoStreamSubscription?.cancel();
return super.close();
}
}
Even containing data in the database it comes empty, I need help to know where the problem is.

Why I got : Error: MissingPluginException(No implementation found for method startScan on channel flutter_bluetooth_brazilian/methods)?

I'm trying to connect devices with Bluetooth and then share data. The problem now is that I always get: Missing Plugin Exception for flutter_bluetooth bluetooth_Brazilian.
this is bluetooth_manager.dart code:
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:rxdart/rxdart.dart';
import 'bluetooth_device.dart';
/// A BluetoothManager.
class BluetoothManager {
static const String NAMESPACE = 'flutter_bluetooth_brazilian';
static const int CONNECTED = 1;
static const int DISCONNECTED = 0;
static const MethodChannel _channel =
const MethodChannel('$NAMESPACE/methods');
static const EventChannel _stateChannel =
const EventChannel('$NAMESPACE/state');
Stream<MethodCall> get _methodStream => _methodStreamController.stream;
final StreamController<MethodCall> _methodStreamController =
StreamController.broadcast();
BluetoothManager._() {
_channel.setMethodCallHandler((MethodCall call) {
_methodStreamController.add(call);
return;
});
}
static BluetoothManager _instance = BluetoothManager._();
static BluetoothManager get instance => _instance;
// Future<bool> get isAvailable async =>
// await _channel.invokeMethod('isAvailable').then<bool>((d) => d);
// Future<bool> get isOn async =>
// await _channel.invokeMethod('isOn').then<bool>((d) => d);
Future<bool> get isConnected async =>
await _channel.invokeMethod('isConnected');
BehaviorSubject<bool> _isScanning = BehaviorSubject.seeded(false);
Stream<bool> get isScanning => _isScanning.stream;
BehaviorSubject<List<BluetoothDevice>> _scanResults =
BehaviorSubject.seeded([]);
Stream<List<BluetoothDevice>> get scanResults => _scanResults.stream;
PublishSubject _stopScanPill = new PublishSubject();
/// Gets the current state of the Bluetooth module
Stream<int> get state async* {
yield await _channel.invokeMethod('state').then((s) => s);
yield* _stateChannel.receiveBroadcastStream().map((s) => s);
}
/// Starts a scan for Bluetooth Low Energy devices
/// Timeout closes the stream after a specified [Duration]
Stream<BluetoothDevice> scan({
Duration timeout,
}) async* {
if (_isScanning.value == true) {
throw Exception('Another scan is already in progress.');
}
// Emit to isScanning
_isScanning.add(true);
final killStreams = <Stream>[];
killStreams.add(_stopScanPill);
if (timeout != null) {
killStreams.add(Rx.timer(null, timeout));
}
// Clear scan results list
_scanResults.add(<BluetoothDevice>[]);
try {
await _channel.invokeMethod('startScan');
} catch (e) {
print('Error starting scan.');
_stopScanPill.add(null);
_isScanning.add(false);
throw e;
}
yield* BluetoothManager.instance._methodStream
.where((m) => m.method == "ScanResult")
.map((m) => m.arguments)
.takeUntil(Rx.merge(killStreams))
.doOnDone(stopScan)
.map((map) {
final device = BluetoothDevice.fromJson(Map<String, dynamic>.from(map));
final List<BluetoothDevice> list = _scanResults.value;
int newIndex = -1;
list.asMap().forEach((index, e) {
if (e.address == device.address) {
newIndex = index;
}
});
if (newIndex != -1) {
list[newIndex] = device;
} else {
list.add(device);
}
_scanResults.add(list);
return device;
});
}
Future startScan({
Duration timeout,
}) async {
await scan(timeout: timeout).drain();
return _scanResults.value;
}
/// Stops a scan for Bluetooth Low Energy devices
Future stopScan() async {
await _channel.invokeMethod('stopScan');
_stopScanPill.add(null);
_isScanning.add(false);
}
Future<dynamic> connect(BluetoothDevice device) =>
_channel.invokeMethod('connect', device.toJson());
Future<dynamic> disconnect() => _channel.invokeMethod('disconnect');
Future<dynamic> destroy() => _channel.invokeMethod('destroy');
Future<dynamic> writeData(List<int> bytes) {
Map<String, Object> args = Map();
args['bytes'] = bytes;
args['length'] = bytes.length;
_channel.invokeMethod('writeData', args);
return Future.value(true);
}
}
flutter_bluetooth_brazilian doesn't support the web platform. You can check the supported platforms right on the plugin's page at https://pub.dev.

Mokito wont return a stubbed value

I started TDD recently and it has slowed my progress, I m trying to stub a return value with Mockito, but i keep getting "null is not a subtype of Future-dynamic' not sure what i did wrong, here is my setup
class ImageSelectorMock extends Mock implements ImageSelector {}
getImageSelectorMock({logo}) {
_unregisterIfRegistered<ImageSelector>();
var imageSelector = ImageSelectorMock();
if (logo != null) {
when(imageSelector.businessLogo).thenReturn('string');
when(imageSelector.uploadImage(null, 'folder'))
.thenAnswer((realInvocation) async =>
Future.value('send this')
);
}
locator.registerSingleton<ImageSelector>(imageSelector);
return imageSelector;
}
setupService() {
//getAuthServiceMock();
//getFirestoreServiceMock();
//getNavigationServiceMock();
getImageSelectorMock();
}
void _unregisterIfRegistered<T extends Object>() {
if (locator.isRegistered<T>()) {
locator.unregister<T>();
}
}
getImageSelectorMock takes an optional arg "logo" to check if imageSelector.uploadImage is called. Also, I'm using a locator/get_it package
group('RegistrationviewmodelTest -', () {
setUp(() => {setupService()});
test('when business logo is NOT null => uplaodImage should be called', () async {
// final navigation = getNavigationServiceMock();
// final fireStore = getFirestoreServiceMock();
final imageSelector = await getImageSelectorMock(logo: "test");
final model = RegistraionViewModel();
await model.createBusiness({
'title': "text",
'description': "text",
});
verify(imageSelector.uploadImage('', 'upload'));
// verify(navigation.navigateTo());
});
});
// uploadImage does
Future uploadImage(file, folder) async {
// String fileName = basename(_imageFile.path);
String fileName = basename(file.path);
final firebaseStorageRef =
FirebaseStorage.instance.ref().child('$folder/$fileName');
final uploadTask = firebaseStorageRef.putFile(file);
final taskSnapshot = await uploadTask;
return taskSnapshot.ref.getDownloadURL().then((value) => value);
}
uploadImage is just an image picker that returns download Url from fire storege.
Thanks for helping out!!

flutter context become null if list is not empty

I have a form to create/update activity which is a stateful widget like this:
class ActivityForm extends StatefulWidget {
final Activity activity;
final bool isEdit;
const ActivityForm({Key key, this.activity, this.isEdit}) : super(key: key);
#override
_ActivityFormState createState() => _ActivityFormState();
}
class _ActivityFormState extends State<ActivityForm> {
final _formKey = GlobalKey<FormState>();
List<int> activityDetailIdToBeDeleted;
...
void submitHandler() async {
setState(() {
_isLoading = true;
});
// Mapping input field to activity model
Activity activity = Activity(
id: widget.activity.id,
tanggal: _tanggalController.text,
uraianKegiatan: _uraianKegiatanController.text,
pic: _picController.text,
jumlahTim: int.parse(_jumlahTimController.text),
kendala: _kendalaController.text,
penyelesaian: _penyelesaianController.text,
approverUserId: selectedApprovalUser,
rincianPekerjaan: rincianPekerjaanList,
status: 'PENDING');
if (widget.isEdit) {
await Provider.of<ActivityProvider>(context, listen: false)
.updateActivity(activity, activityDetailIdToBeDeleted);
} else {
await Provider.of<ActivityProvider>(context, listen: false)
.createActivity(activity);
}
Navigator.pop(context);
}
in my form there are some detail list of activities. When i press delete it adds the id of
the activity detail to the list of "to be deleted" :
IconButton(
icon: Icon(Icons.delete),
onPressed: () => removeRincianPekerjaan(
activityDetail.description),),
here's the function:
void removeRincianPekerjaan(desc) {
if (widget.isEdit) {
int detailId = rincianPekerjaanList
.where((element) => element.description == desc)
.first
.id;
if (!activityDetailIdToBeDeleted.contains(detailId))
activityDetailIdToBeDeleted.add(detailId);
print(activityDetailIdToBeDeleted);
}
setState(() {
rincianPekerjaanList
.removeWhere((element) => element.description == desc);
});
}
that list of ids will be sent to provider which looks like this:
Future<bool> updateActivity(
Activity activity, List<int> activityDetailToBeDeleted) async {
final response = await ActivityService()
.updateActivity(activity.id.toString(), activity.toMap());
if (response != null) {
// Update Success.
if (response.statusCode == 200) {
var body = json.decode(response.body);
removeActivityToList(activity);
activity = Activity.fromMap(body['activity']);
addActivityToList(activity);
if (activityDetailToBeDeleted.isNotEmpty) {
print("to be deleted is not empty.");
print("ID to be deleted: ${activityDetailToBeDeleted.join(",")}");
final res = await ActivityService()
.deleteActivityDetail(activityDetailToBeDeleted.join(","));
if (res.statusCode == 204) {
print('ID DELETED.');
return true;
}
}
return true;
}
// Error unauthorized / token expired
else if (response.statusCode == 401) {
var reauth = await AuthProvider().refreshToken();
if (reauth) {
return await createActivity(activity);
} else {
return Future.error('unauthorized');
}
}
return Future.error('server error');
}
return Future.error('connection failed');
}
the problem is if the list is empty, or i didn't add the id to the list, builder context is not null but if i add an id to the list "to be deleted", the Navigator.pop(context) will throw an error because context is null. I don't understand why it becomes null.
full code in here
Your [context] must came from the build() method. Like this.
void submitHandler(BuildContext context) async {
setState(() {
_isLoading = true;
});
// Mapping input field to activity model
Activity activity = Activity(
id: widget.activity.id,
tanggal: _tanggalController.text,
uraianKegiatan: _uraianKegiatanController.text,
pic: _picController.text,
jumlahTim: int.parse(_jumlahTimController.text),
kendala: _kendalaController.text,
penyelesaian: _penyelesaianController.text,
approverUserId: selectedApprovalUser,
rincianPekerjaan: rincianPekerjaanList,
status: 'PENDING');
if (widget.isEdit) {
await Provider.of<ActivityProvider>(context, listen: false)
.updateActivity(activity, activityDetailIdToBeDeleted);
} else {
await Provider.of<ActivityProvider>(context, listen: false)
.createActivity(activity);
}
SchedulerBinding.instance.addPostFrameCallback((_) {
Navigator.pop(context);
});
}