Showing dialog with bottom navigationbar flutter - flutter

I want to show Dialog instead of function using bottom navigation bar in flutter.How can I implement that?
#override
Widget build(BuildContext context) {
Widget child = Container();
switch(_selectedIndex) {
case 0:
child = function_1();
print("done");
break;
case 1:
child = function_1();
break;
}
When I use ShowDialog method It says:
The following assertion was thrown building ServerGrid(dirty; state: _ServerGridState#59211289()):
I/flutter (14351): setState() or markNeedsBuild() called during build.
I/flutter (14351): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter (14351): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter (14351): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter (14351): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter (14351): Otherwise, the framework might not visit this widget during this build phase.

Related

Getx setState() or markNeedsBuild() called during build

im using Getx for my state management so the case is i have a screen with detail of the video and a list tile for another suggested video. in the screen i call initstate to call Getx function to fetch the video detail data like this
the point is what is the proper way to call getx function on screen build is it only with initState? if i use onInit in the controller it only initialize upon the controller build not the screen build
// video detail screen
#override
void initState() {
super.initState();
videoC.getVideoDetail(videoId: widget.data);
}
// get video detail
var videoDetailLoading = false.obs;
var videoDetail = {}.obs;
getVideoDetail({videoId}) {
videoDetail.clear();
videoDetailLoading.value = true;
String endpoint = 'video/$videoId';
http.get(endpoint).then(
(res) {
log('$endpoint item === $res');
if (res['status']) {
videoDetail.value = res['data'];
videoDetail.refresh();
} else {}
videoDetailLoading.value = false;
},
).catchError((onError) {
videoDetailLoading.value = false;
// Get.back();
// Helper().snakbar(isSuccess: false, message: 'Layar tidak tersedia');
log('$endpoint onError === $onError');
});
}
but after i navigate to the detail screen by tapping the suggested video
(basically it just navigate to the same screen but different data) then it throws this error
This Obx widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: Obx
has builder
state: _ObxState#45cea
The widget which was currently being built when the offending call was made was: Builder
The relevant error-causing widget was
GetMaterialApp
lib/main.dart:16
When the exception was thrown, this was the stack
what is the proper way to call getx function on screen build is it only with initState? if i use onInit in the controller it only initialize upon the controller build not the screen build
Your screen is refreshing before it's not loaded fully so getting this error, Please try with below code.
video detail screen
#override
void initState() {
super.initState();
WidgetBinding.instance.addPostFrameCallBack((timeStamp){
videoC.getVideoDetail(videoId: widget.data);
});
}

Flutter Navigation 2.0 + Bloc

I am currently trying to learn Navigation 2.0 in conjunction with BLoC.
I've followed the raywenderlich's guide [1] successfully (it's a bit outdated) and i tried to move forward managing the state with BLoC (this guide uses Provider) and when i did it successfully, i tried to take a step further and i tried to follow JalalOkbi's guide [2] because of a more advanced abstraction level provided. The third link [3] is the github repo with the full (now failing) project.
But after 5 days of trying i stumbled in several errors and i can't figure this out: i am currently facing this error:
I/flutter (10212): looking for /
I/flutter (10212): found Splash("null", null, null)
I/flutter (10212): looking for /
I/flutter (10212): found Splash("null", null, null)
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Builder:
The settings getter of a page-based Route must return a Page object. Please set the settings to the Page in the Page.createRoute method.
'package:flutter/src/widgets/navigator.dart':
package:flutter/…/widgets/navigator.dart:1
Failed assertion: line 3361 pos 9: 'entry.route.settings == page'
════════ Exception caught by widgets library ═══════════════════════════════════
A GlobalKey was used multiple times inside one widget's child list.
The relevant error-causing widget was
MaterialApp
lib\main.dart:40
════════════════════════════════════════════════════════════════════════════════
[1] https://www.raywenderlich.com/19457817-flutter-navigator-2-0-and-deep-links
[2] https://medium.com/#JalalOkbi/flutter-navigator-2-0-with-bloc-the-ultimate-guide-6672b115adf
[3] https://github.com/msimoncini90/flutter_navigation_2.0
If your page object is defined like
class SplashPage extends Page {
#override
Route createRoute(BuildContext context) {
return MaterialPageRoute(
builder: (BuildContext context) => const SplashScreen(),
);
}
}
The issue is that there is a missing setting in the page definition, which is what the error is showing. The correct code looks like
class SplashPage extends Page {
#override
Route createRoute(BuildContext context) {
return MaterialPageRoute(
settings: this,
builder: (BuildContext context) => const SplashScreen(),
);
}
}
Notice that the settings: this parameter, which solves what the error is describing.

When I make Widget build in flutter, can I make it without Scaffold?

I'm trying to make an app with just a webview with flutter.
1). When I make Widget build, can I make it without Scaffold like the code below?
2). I want to reduce even one frame.
If I build without scaffold will it help reduce frames?
And 3). I'm only making webviews, can I remove SafeArea as well?
return Container(
child: SafeArea(
child: WebView(
..
),
)
);
}
To answer your question shortly:
The Scaffold or a Material widget is required if your widget is a Widget (such as TextField) that required a Material parent widget. No if your widget is not.
If you omit the Material parent widget, an error will happens (See the end of the post for more info).
In this case, since your widget is a WebView (which I assume is from this package webview_flutter), you don't need a Scaffold.
You can simply use it like this:
import 'dart:io';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatefulWidget {
#override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewExample> {
#override
Widget build(BuildContext context) {
return WebView(
initialUrl: 'https://flutter.dev',
);
}
}
P/s: The error when you omit a Material parent will be like:
I/flutter ( 5187): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5187): The following assertion was thrown building InputDecorator(decoration: InputDecoration(hintText:
I/flutter ( 5187): "Type something"); baseStyle: null; isFocused: false; isEmpty: true; dirty):
I/flutter ( 5187): No Material widget found.
I/flutter ( 5187): InputDecorator widgets require a Material widget ancestor.
I/flutter ( 5187): In material design, most widgets are conceptually "printed" on a sheet of material. In Flutter's
I/flutter ( 5187): material library, that material is represented by the Material widget. It is the Material widget
I/flutter ( 5187): that renders ink splashes, for instance. Because of this, many material library widgets require that
I/flutter ( 5187): there be a Material widget in the tree above them.
I/flutter ( 5187): To introduce a Material widget, you can either directly include one, or use a widget that contains
I/flutter ( 5187): Material itself, such as a Card, Dialog, Drawer, or Scaffold.

setState() or markNeedsBuild() called during build inside a StreamBuilder

I am using this StreamBuilder to get the current location:
StreamBuilder<UserLocation>(
stream: locationService.locationStream,
builder: (context, snapshot) {
if (snapshot.data != null) {
bool es_actual = ubicacionesProvider.ubicacionActualSeleccionada;
bool es_elegida = ubicacionesProvider.ubicacionElegidaSeleccionada;
if(es_actual){
latitudData = snapshot.data.latitude;
// ubicacionesProvider.setlatitudActual(latitudData);
longitudData = snapshot.data.longitude;
//ubicacionesProvider.setlongitudActual(longitudData);
Coordinates misCoordenadas =
new Coordinates(latitudData, longitudData);
// ubicacionesProvider.setubicacionActual(_miDireccionActual);
getAddress(misCoordenadas);
}
if(es_elegida){
_latitudElegida = ubicacionesProvider.latitudElegida;
_longitudElegida = ubicacionesProvider.longitudElegida;
_miDireccionActual = ubicacionesProvider.ubicacionElegida;
}
}
I want to update a provider called ubicacionesProvider with some changes:
ubicacionesProvider.setlatitudActual(latitudData)
ubicacionesProvider.setlongitudActual(longitudData)
ubicacionesProvider.setubicacionActual(_miDireccionActual)
But I am getting a warning using one or all of them, the app is not exiting but the warning is shown:
======== Exception caught by foundation library ====================================================
The following assertion was thrown while dispatching notifications for UbicacionesProvider:
setState() or markNeedsBuild() called during build.
This _InheritedProviderScope<UbicacionesProvider> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<UbicacionesProvider>
value: Instance of 'UbicacionesProvider'
listening to value
The widget which was currently being built when the offending call was made was: StreamBuilder<UserLocation>
dirty
dependencies: [MediaQuery]
state: _StreamBuilderBaseState<UserLocation, AsyncSnapshot<UserLocation>>#39568
When the exception was thrown, this was the stack:
#0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4292:11)
#1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4307:6)
#2 _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:496:5)
#3 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:226:25)
#4 UbicacionesProvider.setlatitudActual (package:flutter_qplan/providers/ubicaciones_provider.dart:50:5)
...
The UbicacionesProvider sending notification was: Instance of 'UbicacionesProvider'
====================================================================================================
I would like to update the provider without getting that warning.
Usually this happens when you setState or notifyListeners before the build has finished building all the widgets. Maybe you can add your update logic like this :
WidgetsBinding.instance!.addPostFrameCallback((_) {
// Add Your Update Code here.
});

issues with consumers and providers

Hello I am facing an issue with my flutter app using providers and consumer.
everything works fine how ever I have this issue in my debugger:
════════ Exception caught by foundation library ════════════════════════════════
The following assertion was thrown while dispatching notifications for CatergoryProvider:
setState() or markNeedsBuild() called during build.
This _InheritedProviderScope<CatergoryProvider> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<CatergoryProvider>
value: Instance of 'CatergoryProvider'
listening to value
The widget which was currently being built when the offending call was made was: Consumer<CatergoryProvider>
dirty
dependencies: [_InheritedProviderScope<CatergoryProvider>]
When the exception was thrown, this was the stack
#0 Element.markNeedsBuild.<anonymous closure>
package:flutter/…/widgets/framework.dart:4138
#1 Element.markNeedsBuild
package:flutter/…/widgets/framework.dart:4153
#2 _InheritedProviderScopeElement.markNeedsNotifyDependents
package:provider/src/inherited_provider.dart:496
#3 ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:243
#4 CatergoryProvider.setLoading
package:quizz_app/provider/catergoryProvider.dart:43
...
The CatergoryProvider sending notification was: Instance of 'CatergoryProvider'
here is the consumer in question:
Consumer<CatergoryProvider>(
builder: (context, catergory, child) {
if (!catergory.isLoading() && !catergory.isList()) {
catergory.fetchCatergory();
}
catergories = catergory.getList();
return catergory.isLoading()
? ModalProgressHUD(
opacity: 0,
inAsyncCall: catergory.isLoading(),
child: Container())
: catergoryPage(catergories, context);
},
),
and this is where the stack trace leads me to:
void setLoading(value) {
loading = value;
notifyListeners();
}
It looks like you are probably calling setLoading(value) inside of a build method.. This would try to trigger a rebuild of the widget when notifyListeners() is invoked during the build of the widget.
Consider using a FutureBuilder or a StreamBuilder to change state depending when waiting on an async action.