Bad state: No ProviderScope found in flutter consumer component - flutter

When I add flutter consumer component in flutter like this:
SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
sliver: Consumer(
(context, read) {
return read(storiesTypeProvider(articleRequest)).when(
loading: () {
// return SliverFillRemaining(
// child: Center(child: CircularProgressIndicator()));
return SliverToBoxAdapter(child: Center(child: LoadingItem()));
},
error: (err, stack) {
print(err);
return SliverToBoxAdapter(
child: Center(child: Text('Error: $err')));
},
data: (ids) {
//return StoryList(ids: ids,storiesType: articleRequest.storiesType,);
},
);
},
),
)
shows this error:
flutter: [debug] Capture from onError 'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
flutter: [debug] Capture from onError 'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
======== Exception caught by widgets library =======================================================
The following StateError was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#0ac5b](state: RawGestureDetectorState#734b4(gestures: <none>, behavior: opaque)):
Bad state: No ProviderScope found
The relevant error-causing widget was:
SmartRefresher file:///Users/dolphin/Documents/GitHub/cruise-open/lib/src/page/home/components/homelistdefault_component/view.dart:47:22
When the exception was thrown, this was the stack:
#0 ProviderStateOwnerScope.of (package:flutter_riverpod/src/framework.dart:216:7)
#1 _ConsumerState.didChangeDependencies (package:flutter_riverpod/src/consumer.dart:107:46)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4839:11)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4655:5)
... Normal element mounting (4 frames)
...
====================================================================================================
======== Exception caught by scheduler library =====================================================
'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
====================================================================================================
======== Exception caught by scheduler library =====================================================
'package:flutter/src/widgets/nested_scroll_view.dart': Failed assertion: line 806 pos 14: 'position.hasContentDimensions && position.hasPixels': is not true.
====================================================================================================
now I am using fish-redux to manage my flutter state, should I must using ProviderScope? what should I do to fix this problem? this is the storiesTypeProvider:
final storiesTypeProvider = FutureProvider.family((ref, type) async {
return await Repo.getArticles(type);
});

If you use flutter_riverpod.
You need to add ProviderScope to the main() function.
Like this:
void main() {
runApp(ProviderScope(child: MyApp()));
}

Related

The method 'containsKey' was called on null flutter

Before, my integration test works. After I pull an update of another developer my integration test fails with the following error:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following NoSuchMethodError was thrown running a test:
The method 'containsKey' was called on null.
Receiver: null
Tried calling: containsKey("serverStatus")
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1 _IndexState._referAFriendEnabled (package:limitless/pages/index.dart:1390:15)
Transition { currentState: HomeInitial(), event: FetchHomeCarousels(), nextState: HomeInitial() }
Transition { currentState: InitialInboxState(), event: InboxFetch(), nextState: InboxFetchingData() }
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test (but after the test had completed):
'package:flutter_test/src/binding.dart': Failed assertion: line 1558 pos 12: 'inTest': is not true.
When the exception was thrown, this was the stack:
#2 LiveTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:1558:12)
#3 WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:668:23)
<asynchronous suspension>
<asynchronous suspension>
(elided 3 frames from class _AssertionError and package:stack_trace)
════════════════════════════════════════════════════════════════════════════════════════════════════
03:29 +0 -1: end-to-end test limitless non-transactional test
CustomerStart { }
Transition { currentState: CustomerInitial(), event: CustomerStart { }, nextState: CustomerLoading() }
03:31 +0 -1: Some tests failed.
Running the app works fine. It only fails when running integration test.
This is code snippet about containsKey.
void _referAFriendEnabled() async {
bool referralEnabled = false;
PackageInfo packageInfo = await PackageInfo.fromPlatform();
if (prefs.containsKey('serverStatus')) {
Map appSettings = await AppSharedPref.getServerStatus();
limitlessRepo.appVersion = appSettings["app_version"];
limitlessRepo.storeVersion = appSettings["latest_store_app_version"];
referralEnabled = appSettings["referral_code"];
limitlessRepo.version = packageInfo.version;
} else {
await limitlessRepo.isReferralCodeEnabled();
}
newVersionAvailable();
setState(() {
_isReferralEnabled = referralEnabled;
});
Does anyone has an idea about this? Thank you.

The following assertion was thrown running a test: pumpAndSettle timed out Flutter

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
pumpAndSettle timed out
When the exception was thrown, this was the stack:
#0 WidgetTester.pumpAndSettle. (package:flutter_test/src/widget_tester.dart:667:11)
(elided one frame from package:stack_trace)
This post helped me when I faced this issue
https://cursos.alura.com.br/forum/topico-pumpandsettle-timed-out-175044
so basically remove the tester.pumpAndSettle()
and replace it with
for (int i = 0; i < 5; i++) { await tester.pump(Duration(seconds: 1)); }

Advance PDF Viewer : Failed assertion: line 4263 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true

I am getting the error when I try to load the pdf from URL.
It shows the number of pages of pdf but then error appears on the screen.
Using plugin - https://pub.dev/packages/advance_pdf_viewer
Logcat:
======== Exception caught by widgets library
=======================================================
The following _CastError was thrown building NotificationListener<KeepAliveNotification>:
Null check operator used on a null value
The relevant error-causing widget was:
PDFViewer file:///D:/GST%20with%20GT/gst_with_gt/lib/screens/pdfview.dart:70:19
When the exception was thrown, this was the stack:
#0 _PDFPageState._repaint (package:advance_pdf_viewer/src/page.dart:54:45)
#1 _PDFPageState.didChangeDependencies (package:advance_pdf_viewer/src/page.dart:42:5)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4725:11)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4541:5)
#4 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3603:14)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following assertion was thrown building SliverFillViewport:
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 258 pos 16: 'child == null || indexOf(child) > index': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
The relevant error-causing widget was:
PDFViewer file:///D:/GST%20with%20GT/gst_with_gt/lib/screens/pdfview.dart:70:19
When the exception was thrown, this was the stack:
#2 RenderSliverMultiBoxAdaptor._debugVerifyChildOrder (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:258:16)
#3 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled=.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:233:14)
#4 RenderSliverMultiBoxAdaptor.debugChildIntegrityEnabled= (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:235:6)
#5 SliverMultiBoxAdaptorElement.performRebuild (package:flutter/src/widgets/sliver.dart:1208:20)
#6 SliverMultiBoxAdaptorElement.update (package:flutter/src/widgets/sliver.dart:1124:7)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following assertion was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#411e6](state: RawGestureDetectorState#4acaf(gestures: <none>, behavior: opaque)):
A RenderViewport expected a child of type RenderSliver but received a child of type RenderErrorBox.
RenderObjects expect specific types of children because they coordinate with their children during layout and paint. For example, a RenderSliver cannot be the child of a RenderBox because a RenderSliver does not understand the RenderBox layout protocol.
The RenderViewport that expected a RenderSliver child was created by: Viewport ← IgnorePointer-[GlobalKey#e5bfe] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#411e6] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#3ad9e] ← RepaintBoundary ← CustomPaint ← RepaintBoundary ← ⋯
The RenderErrorBox that did not match the expected child type was created by: ErrorWidget-[#87a59] ← SliverFillViewport ← Viewport ← IgnorePointer-[GlobalKey#e5bfe] ← Semantics ← Listener ← _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#411e6] ← Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#3ad9e] ← RepaintBoundary ← ⋯
The relevant error-causing widget was:
PDFViewer file:///D:/GST%20with%20GT/gst_with_gt/lib/screens/pdfview.dart:70:19
When the exception was thrown, this was the stack:
#0 ContainerRenderObjectMixin.debugValidateChild.<anonymous closure> (package:flutter/src/rendering/object.dart:3134:9)
#1 ContainerRenderObjectMixin.debugValidateChild (package:flutter/src/rendering/object.dart:3161:6)
#2 MultiChildRenderObjectElement.insertRenderObjectChild (package:flutter/src/widgets/framework.dart:6127:25)
#3 RenderObjectElement.attachRenderObject (package:flutter/src/widgets/framework.dart:5737:35)
#4 RenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5433:5)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following assertion was thrown building _ScrollableScope:
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4263 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
The relevant error-causing widget was:
PDFViewer file:///D:/GST%20with%20GT/gst_with_gt/lib/screens/pdfview.dart:70:19
When the exception was thrown, this was the stack:
#2 Element.rebuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4263:14)
#3 Element.rebuild (package:flutter/src/widgets/framework.dart:4266:6)
#4 StatefulElement.update (package:flutter/src/widgets/framework.dart:4771:5)
#5 Element.updateChild (package:flutter/src/widgets/framework.dart:3345:15)
#6 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6057:14)
...
Here, my code :
class PdfViewers extends StatefulWidget {
#override
PdfViewersState createState() => PdfViewersState();
}
class PdfViewersState extends State<PdfViewers> {
bool _isLoadings = true;
PDFDocument docs;
#override
void initState() {
Timer(
Duration(seconds: 1),
() => loadUrl(),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.grey[100],
actions: [
IconButton(
icon: Icon(
Icons.share_rounded,
color: Color(0xff4f2e7f),
),
onPressed: () async {}),
],
title: Text(
'PDF Article',
softWrap: true,
style: TextStyle(color: Color(0xff4f2e7f)),
),
leading: IconButton(
onPressed: () {
Navigator.pop(context, true);
},
icon: Icon(Icons.arrow_back_outlined, color: Color(0xff4f2e7f))),
),
body: Center(
child: _isLoadings
? Container(child: CircularProgressIndicator())
: PDFViewer(document: docs)));
}
Future<void> loadUrl() async {
setState(() {
_isLoadings = true;
});
docs= await PDFDocument.fromURL(
'https://gstwithgt.fivestake.com/uploads/topics/16254191793470.pdf');
setState(() {
_isLoadings = false;
});
}
}
I tried and searched many tutorials and example but none of them are working for me. so I posted question here.
The main thing is when I paste this same code in another project then it is working fine. I don't know where the problem is.. I'm trying to solve this error since last two days..
I also faced the same issue.
You can find here the full discussion: https://github.com/lohanidamodar/pdf_viewer/issues/62
It seems that on the first try to open the file it returns null from here:
var data = await _channel .invokeMethod('getPage', {'filePath': _filePath, 'pageNumber': page});
(From document.dart file)
The interesting thing is that after I reopen my app everything works fine.
This patch solved this exception for me:
I have noticed that before I reopen the application (which solves the issue) and I try to open the PDF, I'm getting this exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.app.Activity.getResources()' on a null object reference
But when I reopen the app and everything works, this exception disappears. So, I have looked for this exception in this repository issues and encountered this fix:
https://github.com/lohanidamodar/pdf_viewer/issues/45
After implementing RasyidMF solution, the PDF opens correctly.

'package:flutter/src/gestures/tap.dart': Failed assertion: line 201 pos 14: '_down == null && _up == null': is not true

I am using gesture tap to close the article detail page, when I reopen the article detail page, the app will show this error(the first time open the detail works fine, the second time open the detail will show this error and the detail could not roll up and down):
======== Exception caught by gesture library =======================================================
The following assertion was thrown while dispatching a pointer event:
'package:flutter/src/gestures/tap.dart': Failed assertion: line 201 pos 14: '_down == null && _up == null': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
When the exception was thrown, this was the stack:
#2 BaseTapGestureRecognizer.addAllowedPointer (package:flutter/src/gestures/tap.dart:201:14)
#3 GestureRecognizer.addPointer (package:flutter/src/gestures/recognizer.dart:102:7)
#4 RawGestureDetectorState._handlePointerDown (package:flutter/src/widgets/gesture_detector.dart:1204:18)
#5 RenderPointerListener.handleEvent (package:flutter/src/rendering/proxy_box.dart:2821:29)
#6 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:361:22)
...
Event: PointerDownEvent#6e7c4(position: Offset(191.4, 563.1))
position: Offset(191.4, 563.1)
Target: RenderPointerListener#946e9 relayoutBoundary=up46
parentData: <none> (can use size)
constraints: BoxConstraints(0.0<=w<=363.4, 0.0<=h<=Infinity)
size: Size(363.4, 458.2)
behavior: deferToChild
listeners: down
====================================================================================================
and this is my detail page flutter code:
return GestureDetector(
onHorizontalDragStart: _onHorizontalDragStart,
onHorizontalDragUpdate: _onHorizontalDragUpdate,
onHorizontalDragEnd: _onHorizontalDragEnd,
child: Container(
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height * 0.9,
),
color: Theme.of(context).scaffoldBackgroundColor,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: buildListView(item, context),
),
));
void _onHorizontalDragStart(DragStartDetails details) {
_initialSwipeOffset = details.globalPosition;
}
void _onHorizontalDragUpdate(DragUpdateDetails details) {
_finalSwipeOffset = details.globalPosition;
}
void _onHorizontalDragEnd(DragEndDetails details) {
if (_initialSwipeOffset != null) {
final offsetDifference = _initialSwipeOffset!.dx - _finalSwipeOffset!.dx;
if (offsetDifference < 0) {
Navigator.pop(context);
}
}
}
I am searching from internet but find no one encount this problem. what should I do to fix this problem?
It looks like you are using a pre-release version of Flutter SDK. I recommend you use Flutter Stable channel and rebuild your project again.
according to Flutter build release channels
the stable version is recommended for all production app releases.
Now to know which branch you are currently using. open the terminal and type the following command.
flutter channel
The channel which you are on will be displayed with '*' at the beginning. E.g,
*master
dev
beta
stable
To change to the stable channel, run this command on your terminal.
flutter channel CHANNEL_NAME
For example, change the channel to stable,
flutter channel stable
To ensure that you're on the latest build from this channel, run
flutter upgrade
This is all you need to do.

Prevent "Tried to use Provider with a subtype of Listenable/Stream" flutter error

I want to use the provider package(4.0) in my flutter project but i get the "Tried to use Provider with a subtype of Listenable/Stream" error/warning.
My constelation:
I have an Api() class which contains base CRUD functionality for firebase-cloudstorage.
I have an EventService()-class which uses the Api()-class with a concrete parameter.
For my view i have a ViewModel class called EventOverviewModel which uses the EventService.
My provider configuration looks like this:
List<SingleChildWidget> providers = [
...independentServices,
...dependentServices,
...uiConsumableProviders,
];
// Services die unabhängig von anderen sind
List<SingleChildWidget> independentServices = [
Provider<EventService>(create: (_) => EventService(api: Api('events')))
];
// Services die von anderen Services abhängig sind
List<SingleChildWidget> dependentServices = [
ProxyProvider<EventService, EventOverviewModel>(
update: (_, srvc, __) => EventOverviewModel(eventService: srvc),
)
];
List<SingleChildWidget> uiConsumableProviders = [];
Everything seems to work in the application but i get the "Tried to use Provider with a subtype of Listenable/Stream" anyway.
How should i change my code to not getting this error message anymore?
Running Gradle task 'assembleDebug'...
I/flutter (16553): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (16553): The following assertion was thrown building NumericProxyProvider<EventService, Void, Void, Void,
I/flutter (16553): Void, Void, EventOverviewModel>(dirty, dependencies: [InheritedProvider<EventService>], state:
I/flutter (16553): _ProxyProviderState<EventOverviewModel>#8d38d):
I/flutter (16553): Tried to use Provider with a subtype of Listenable/Stream (EventOverviewModel).
I/flutter (16553):
I/flutter (16553): This is likely a mistake, as Provider will not automatically update dependents
I/flutter (16553): when EventOverviewModel is updated. Instead, consider changing Provider for more specific
I/flutter (16553): implementation that handles the update mechanism, such as:
I/flutter (16553):
I/flutter (16553): - ListenableProvider
I/flutter (16553): - ChangeNotifierProvider
I/flutter (16553): - ValueListenableProvider
I/flutter (16553): - StreamProvider
I/flutter (16553):
I/flutter (16553): Alternatively, if you are making your own provider, consider using InheritedProvider.
I/flutter (16553):
I/flutter (16553): If you think that this is not an error, you can disable this check by setting
I/flutter (16553): Provider.debugCheckInvalidValueType to `null` in your main file:
I/flutter (16553):
I/flutter (16553): ```
I/flutter (16553): void main() {
I/flutter (16553): Provider.debugCheckInvalidValueType = null;
I/flutter (16553):
I/flutter (16553): runApp(MyApp());
I/flutter (16553): }
I/flutter (16553): ```
I/flutter (16553):
I/flutter (16553):
I/flutter (16553): The relevant error-causing widget was:
I/flutter (16553): NumericProxyProvider<EventService, Void, Void, Void, Void, Void, EventOverviewModel>
I/flutter (16553): file:///E:/Dev/flutter/.pub-cache/hosted/pub.dartlang.org/provider-3.2.0/lib/src/proxy_provider.dart:232:12
I/flutter (16553):
I/flutter (16553): When the exception was thrown, this was the stack:
I/flutter (16553): #0 Provider.debugCheckInvalidValueType.<anonymous closure>.<anonymous ...
Try changing
List<SingleChildWidget> independentServices = [
Provider<EventService>(create: (_) => EventService(api: Api('events')))
];
to:
List<SingleChildWidget> independentServices = [
ListenableProvider<EventService>(create: (_) => EventService(api: Api('events')))
];
And
List<SingleChildWidget> dependentServices = [
ProxyProvider<EventService, EventOverviewModel>(
update: (_, srvc, __) => EventOverviewModel(eventService: srvc),
)
];
to:
List<SingleChildWidget> dependentServices = [
ListenableProxyProvider<EventService, EventOverviewModel>(
update: (_, srvc, __) => EventOverviewModel(eventService: srvc),
)
];
I'm guessing EventService or EventOverviewModel extend or mixin ChangeNotifier and somewhere in your code you are listening for changes in values of Provider<EventService> and ProxyProvider<EventOverviewModel>, but those changes will never be broadcast/received unless your providers are "Listenable".
So if your models extend/mixin ChangeNotifier, and they are calling notifyListeners(), providers of those models need to be at least "Listenable".
ListenableProvider
ListenableProxyProvider
... or better yet, your models could use ChangeNotifier versions:
ChangeNotifierProvider
ChangeNotifierProxyProvider
... which conveniently disposes / detaches any listeners (frees up resources) when these objects are no longer in use.
When using the Provider package, there are a few issues. All provider instances declared in the in the providers:[] are not listenable by default. As such you need to initialize them as such by using either ChangeNotifierProvider(create: (_) =>Model()) or ListenableProvider(create: (_) =>Model()) or StreamProvider(create: (_) =>Model()) in this case
List<SingleChildWidget> independentServices = [
ChangeNotifierProvider<EventService>(create: (_) => EventService(api: Api('events')))
];
// Services die von anderen Services abhängig sind
List<SingleChildWidget> dependentServices = [
ChangeNotifierProxyProvider<EventService, EventOverviewModel>(
update: (_, srvc, __) => EventOverviewModel(eventService: srvc),
)
];