flutter streams bloc to show handle visible state - flutter

I have a widget isLive that changes state based on the value returned by the bloc.However everytime i run the app i get
The getter 'progressStateStream' was called on null
I tried following this answer
Widget isLive() {
return Container(
child: StreamBuilder<bool>(
stream: _bloc.progressStateStream,
builder: (context, snapshot) {
return Visibility(
maintainState: true,
visible: snapshot.data ?? false,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Container(
color: Colors.pink[50],
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text("yaay i'm visible"),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Text(
"hide"
),
color: Colors.white,
onPressed: () {
_bloc.changeProgressState(state: false);
},
)
],
),
),
),
);
},
));
}
here is my bloc
//this Subject allows sending data, error and done events to the listener
final PublishSubject<bool> _progressStateSubject = new PublishSubject();
//the listener are streaming on changes
Observable<bool> get progressStateStream => _progressStateSubject.stream;
//to change your progress state
void changeProgressState({bool state}) => _progressStateSubject.sink.add(state);
Also if i wanted to save state with hydrated bloc how would I go about it

fixed it by initialising my bloc in init state by adding the bloc to init state
_bloc = RBloc();
_bloc.progressStateStream;

Related

How to change dismissible boolean of modalBottomSheet in flutter after its displayed

I am showing a bottomsheet in flutter by default the isDismissible = false dismissible is set to false but based on certain conditions i want to change this to true i have tried passing a bool to showModalBottomSheet method and changing its value from inside the child widget using setState method but its not working. Any help would be really appreciated.
below is my code for showing bottomsheet
openBottomDialog<T extends StateStreamableSource<Object?>>(
{required BuildContext context,
required Widget child,
double? height,
Function? onClose,
bool? dismissible,
Function? onStateChange}) {
return showModalBottomSheet(
context: context,
barrierColor: AppColors.of(context).semiTransparentBackgroundColor,
backgroundColor: AppColors.of(context).semiTransparentBackgroundColor,
isScrollControlled: true,
isDismissible: dismissible ?? false,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(24.r))),
builder: (model) {
return BlocProvider.value(
value: BlocProvider.of<T>(context),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
child: Wrap(
children: [
Container(
decoration: BoxDecoration(
color: AppColors.of(context).d15151AwF5F5F5,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(24.r),
topRight: Radius.circular(24.r))),
// margin: const EdgeInsets.symmetric(horizontal: 10),
child: Container(
margin: const EdgeInsets.all(8),
child: Column(
children: [
AppAsset(
key: const Key('close_bottom_sheet'),
onTap: () {
Navigator.pop(context);
onClose!();
},
asset: AppImages.line,
tintColor:
AppColors.of(context).bottomSheetHandleColor,
),
Container(child: child)
],
)),
)
],
),
));
});
}
the child widget is a state full widget and inside that i am using setState method to update this variable.
setState(() {
widget.dismissible = false;
countdownTimer.cancel();
sliderState = SlideState.loading;
});

Another exception was thrown: setState() or markNeedsBuild() called during build Error in flutter

Im new to flutter and working on an ecommerce flutter app. When im trying to navigate to search screen its giving some error. Please find the below codes for your reference and help to resolve.
Error :
The following assertion was thrown while dispatching notifications for SearchProvider:
setState() or markNeedsBuild() called during build.
This _InheritedProviderScope<SearchProvider?> 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<SearchProvider?>
The widget which was currently being built when the offending call was made was:
SearchScreen
Codes
Search Screen
class SearchScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
Provider.of<SearchProvider>(context, listen: false).cleanSearchProduct();
Provider.of<SearchProvider>(context, listen: false).initHistoryList();
return Scaffold(
backgroundColor: ColorResources.getIconBg(context),
resizeToAvoidBottomInset: true,
body: Column(
children: [
// for tool bar
SearchWidget(
hintText: getTranslated('SEARCH_HINT', context),
onSubmit: (String text) {
Provider.of<SearchProvider>(context, listen: false)
.searchProduct(text, context);
Provider.of<SearchProvider>(context, listen: false)
.saveSearchAddress(text);
},
onClearPressed: () {
Provider.of<SearchProvider>(context, listen: false)
.cleanSearchProduct();
},
),
Consumer<SearchProvider>(
builder: (context, searchProvider, child) {
return !searchProvider.isClear
? searchProvider.searchProductList != null
? searchProvider.searchProductList.length > 0
? Expanded(
child: SearchProductWidget(
products: searchProvider.searchProductList,
isViewScrollable: true))
: Expanded(
child:
NoInternetOrDataScreen(isNoInternet: false))
: Expanded(
child: ProductShimmer(
isHomePage: false,
isEnabled: Provider.of<SearchProvider>(context)
.searchProductList ==
null))
: Expanded(
flex: 4,
child: Container(
padding:
EdgeInsets.all(Dimensions.PADDING_SIZE_DEFAULT),
child: Stack(
clipBehavior: Clip.none,
children: [
Consumer<SearchProvider>(
builder: (context, searchProvider, child) =>
StaggeredGridView.countBuilder(
crossAxisCount: 3,
physics: NeverScrollableScrollPhysics(),
itemCount: searchProvider.historyList.length,
itemBuilder: (context, index) => Container(
alignment: Alignment.center,
child: InkWell(
onTap: () {
Provider.of<SearchProvider>(context,
listen: false)
.searchProduct(
searchProvider
.historyList[index],
context);
},
borderRadius: BorderRadius.circular(20),
child: Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
top: 2,
bottom: 2),
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(16),
color: ColorResources.getGrey(
context)),
width: double.infinity,
child: Center(
child: Text(
Provider.of<SearchProvider>(context,
listen: false)
.historyList[index] ??
"",
style: titilliumItalic.copyWith(
fontSize:
Dimensions.FONT_SIZE_SMALL),
),
),
),
)),
staggeredTileBuilder: (int index) =>
new StaggeredTile.fit(1),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
),
),
Positioned(
top: -5,
left: 0,
right: 0,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(getTranslated('SEARCH_HISTORY', context),
style: robotoBold),
InkWell(
borderRadius: BorderRadius.circular(10),
onTap: () {
Provider.of<SearchProvider>(context,
listen: false)
.clearSearchAddress();
},
child: Container(
padding: EdgeInsets.all(5),
child: Text(
getTranslated('REMOVE', context),
style: titilliumRegular.copyWith(
fontSize:
Dimensions.FONT_SIZE_SMALL,
color: Theme.of(context)
.primaryColor),
)))
],
),
),
],
),
),
);
},
),
],
),
);
}
}
Providers
void initHistoryList() {
_historyList = [];
_historyList.addAll(searchRepo.getSearchAddress());
notifyListeners();
}
void cleanSearchProduct() {
_searchProductList = [];
_isClear = true;
_searchText = '';
notifyListeners();
}
Try to use initial function calling in initState instead of build function
#override
void initState() {
WidgetsBinding.instance!.addPostFrameCallback((_) {
Provider.of<SearchProvider>(context, listen: false).cleanSearchProduct();
Provider.of<SearchProvider>(context, listen: false).initHistoryList();
});
super.initState();
}

How to display something while the value is null/loading in Flutter?

I've created a real-time object detection with Tiny YOLOv2 using Flutter app. So far the app managed to detect the object and display its bounding box with the detectedClass and confidence. Then I pulled the detectedClass (the name of the object) and assigned it into my String _result variable because I need it to fetch data from Firebase later.
The main issue is when the app is not detecting anything I want to display something like maybe 'Loading...' until the _result return the name of the object bcus u see my custom Tiny YOLOv2 takes a lil bit of time before it detect the object. Then, I want to fetch data based on _result from the Firebase. So far, I've managed to fetch the data from the Firebase BUT ONLY if I hardcoded the name of the object detected. Otherwise the app would return null error if I'm fetching using _result variable.
Below is my attempt of displaying the the name of the food and its calorie (which is fetched from the Firebase) based on the _result variable but FAILED:
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image:AssetImage('assets/back.jpg'), fit: BoxFit.fill),
),
child: Column(
children: [
Stack(
children: [
Center(
child: Container(
margin: EdgeInsets.only(top: 10),
// child: Icon(Icons.photo_camera, color: Colors.orange, size: 40),
child: Text('Press on the camera icon',
style: TextStyle(
fontSize: 16.0,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold
),
textAlign: TextAlign.center,
),
),
),
Center(
child: FlatButton(
onPressed: ()
{
initCamera();
},
child: Container(
margin: EdgeInsets.only(top: 35),
height: 270,
width: 360,
color: Colors.orange,
child: Stack(
children: list,
),
),
),
),
],
),
Center(
child: Container(
margin: EdgeInsets.only(top: 45.0),
child: SingleChildScrollView(
child: FutureBuilder(
future: dbRef.orderByChild("food_name").equalTo(_result).once(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text("Loading..."),
);
} else {
lists.clear();
Map<dynamic, dynamic> values = snapshot.data.value;
values.forEach((key, values) {
lists.add(values);
});
return ListView.builder(
shrinkWrap: true,
itemCount: lists.length,
itemBuilder: (BuildContext context,
int index) {
return
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment
.start,
children: <Widget>[
Text("Name: " + lists[index]["food_name"]),
Text("Calorie: " + lists[index]["calorie"]),
],
),
);
});
}
})
),
),
),
],
),
),
),
),
);
}
}
The error from the above is:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'forEach' was called on null.
Receiver: null
Tried calling: forEach(Closure: (String, dynamic) => Null))
My issue is kinda similar with this user and the solution in there is not working in my case.
I dont know whether its possible to fetch the data from firebase based on the real time input? Otherwise how do I save the name of the object somewhere to make it static(?) I'm really new to Flutter so some guidance on how to code it is very much appreciated. Thank you in advance.
Edited Btw just want to add it here. This is how I declared my _result:
_recognitions.forEach((response)
{
_result = "${response["detectedClass"]}" + "\n\n";
});
Basically _result is just the name of the object detected.
Just wanna share how I resolved this in case anyone's having the same issue. All I did is just insert a while (values == null) inside my else statement like this:
else {
values = snapshot.data.value;
while (values == null){
return Center(
child: CircularProgressIndicator(color: Colors.orange),
);
}
lists.clear();
values.forEach((key, values){
lists.add(values);
});
}
and then followed by the ListView.builder() to display them.
Btw, thank you so much for those who responded!

Why I open this showDialog and after press one of the button, it can't auto close?

When I open this Dialog and after press one of the button, it can't auto close.
Is my navigator wrong? ? How to fix this problem ? Please help me, thanks.
I can’t understand why this pop-up window still stays on the page and my page jumped one page forward, shouldn’t it be popped by the Navigator?
this is my code first widget is the Delete function&UI, second widget is show main List widget, it use ListTile.
Widget _checkDelete({String title, String detail, String uid}) {
ThemeData themeData = Theme.of(context);
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0))),
child: Container(
padding: EdgeInsets.all(16),
decoration: new BoxDecoration(
color: themeData.backgroundColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10.0,
offset: const Offset(0.0, 10.0),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("$title",
style: AppTheme.getTextStyle(
themeData.textTheme.headline6,
fontWeight: FontWeight.w600,
)),
Text("$detail",
style: AppTheme.getTextStyle(
themeData.textTheme.subtitle1,
fontWeight: FontWeight.w400,
)),
Container(
alignment: AlignmentDirectional.centerEnd,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: EdgeInsets.all(0),
splashColor: themeData.colorScheme.primary.withAlpha(150),
onPressed: () {
Navigator.pop(context);
},
child: Text(
"取消",
style: AppTheme.getTextStyle(
themeData.textTheme.bodyText2,
fontWeight: FontWeight.w500,
color: themeData.colorScheme.primary),
)),
FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: EdgeInsets.all(0),
splashColor: themeData.colorScheme.primary.withAlpha(150),
onPressed: () async {
final db = Firestore.instance;
db
.collection('users')
.document(uid)
.updateData({'staff': false}).then((value) =>
showDialog(
context: context,
builder: (BuildContext context) =>
_simpleDialog(
title: '刪除成功',
detail: '已經成功移除客服')));
Navigator.pop(context);
initList();
},
child: Text(
"刪除",
style: AppTheme.getTextStyle(
themeData.textTheme.bodyText2,
fontWeight: FontWeight.w500,
color: Colors.red),
)),
],
),
),
],
),
),
);
}
ThemeData themeData;
ListView _staffList = ListView(
padding: EdgeInsets.all(16),
children: <Widget>[],
);
Future<Null> _onRefresh() async {
await Future.delayed(Duration(milliseconds: 2000));
initList();
return null;
}
initList() async {
final db = Firestore.instance;
db
.collection('users')
.where('staff', isEqualTo: true)
.getDocuments()
.then((datas) {
setState(() {
_staffList = ListView(
padding: EdgeInsets.all(16),
children: <Widget>[
for (var data in datas.documents)
ListTile(
leading: CircleAvatar(
child: Text(data.data['name'][0]),
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () async{
showDialog(
context: context,
builder: (BuildContext context) => _checkDelete(
title: '確定要移除 ${data.data['name']} 的權限嗎?',
detail: '這個帳號將恢復為一般帳號,不會被刪除。',
uid: data.documentID));
}), //this showDialog can't close when I pressed button
subtitle: Text(data.documentID),
title: Text(data.data['name']),
),
],
);
});
});
}
#override
initState() {
super.initState();
initList();
}
There can be multiple Navigator exist in your widget tree. The first one is the root Navigator, and under it there are other nested Navigators.
When you display a dialog, you need to call the showDialog function. This method has a property useRootNavigator that is default to true, which means the dialog route created by this method is pushed to the root Navigator. This is from the documentation:
The useRootNavigator argument is used to determine whether to push the dialog to the [Navigator] furthest from or nearest to the given context. By default, useRootNavigator is true and the dialog route created by this method is pushed to the root navigator. It can not be null`.
In order to pop the Dialog, you need to use the context of the root Navigator as well. Because you are using the context of the nested Navigator, the Dialog is not going away. That's why you need to include the rootNavigator: true in your method calling:
Navigator.of(context, rootNavigator: true).pop()
You can read more about the showDialog method from the documentation here.
do this
showDialog(...,builder:(theContextYouNeedToUse)=>_checkDelete(...,theContextYouNeedToUse));
and in the pop call
_checkDelete(...,BuildContext theContextYouNeedToUse){
...
Navigator.pop(theContextYouNeedToUse);
}
this is happening because, wrong context was used to pop, call to showDialog gives you a new BuildContext to use through the builder function, they have given the builder param for the sole purpose of providing you with the new BuildContext to use further down the tree
see this amazing answer https://stackoverflow.com/a/49100439/12341099

Looking up a deactivated widget's ancestor is unsafe

I am new in Flutter and I am trying receive data with a Dialog.
When a click in textField the error of image2 appear...
show(BuildContext context){
var dialog = Dialog(
child: Container(
margin: EdgeInsets.all(8.0),
child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Insira o número de telefone",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(2.0)))),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancelar")),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Aceitar"))
],
)
],
),
),
),
);
showDialog(context: context,builder: (context){
return dialog;
});
}
This is my code.
I/flutter (31032): Looking up a deactivated widget's ancestor is unsafe.
I/flutter (31032): At this point the state of the widget's element tree is no longer stable. To safely refer to a
I/flutter (31032): widget's ancestor in its dispose() method, save a reference to the ancestor by calling
I/flutter (31032): inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
I/flutter (31032):
Declare a global variable
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
then register the key on your widget build's scaffold eg
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
...
then on the dialog
show(BuildContext context){
var dialog = Dialog(
child: Container(
margin: EdgeInsets.all(8.0),
child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Insira o número de telefone",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(2.0)))),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancelar")),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Aceitar"))
],
)
],
),
),
),
);
Pass that scaffold context to the showDialog method
showDialog(context: _scaffoldKey.currentContext ,builder: (context){
return dialog;
});
}
Try This
Give different context name for dialog
showDialog(context: context,builder: (dialogContex){
return Dialog(
child: Container(
margin: EdgeInsets.all(8.0),
child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Insira o número de telefone",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(2.0)))),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(dialogContex).pop();
},
child: Text("Cancelar")),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Aceitar"))
],
)
],
),
),
),
);
});
I got the same error when attempting to open a dialog and I found a solution here: github flutter issues. Specifically, I followed the poster's recommendation, which was to create a GlobalKey and associate it with the Scaffold widget, and use the context from that key when creating the dialog. In my case, I have a globally accessible object which holds the GlobalKey:
MyGlobals myGlobals = MyGlobals();
class MyGlobals {
GlobalKey _scaffoldKey;
MyGlobals() {
_scaffoldKey = GlobalKey();
}
GlobalKey get scaffoldKey => _scaffoldKey;
}
In the Scaffold widget constructor call:
Scaffold(
appBar: ...,
body: ...,
drawer: ...,
key: myGlobals.scaffoldKey,
)
And in the showDialog call:
showDialog<String>(
barrierDismissible: ...,
builder: ...,
context: myGlobals.scaffoldKey.currentContext,
);
You’re trying to access a context that isn’t probably available. That happens because you’ve assigned your Dialog to a var and afterwards use a different context (the one from your dialog builder).
Either create your dialog directly after your return in the builder or make it a method instead that returns a Dialog and pass it a BuildContext parameter.
Widget myDialog(BuildContext context) => Dialog(/*your dialog here*/);
This is also a more convenient Flutter practice. You should use methods that return widgets instead of assigning it to variables.
use this:
Navigator.of(context,rootNavigator: true).pop();
instead of
Navigator.of(context).pop();
This might happen while you are popping from the context and trying to open new content on the context you are popping.
()async{
Navigator.of(context).pop();
_alertPopUp(); // shows a dialog
// might do some work after
}
if alert dialog is created on current context then it throws an error because context doesn't exist anymore
My problem was that I was using hot reload for pretty long time, I think at some point everything got messed up, doing a normal run of the app fixed the problem.
removing application from emulator and run below commands
flutter clean
flutter pub get
works for me
Though you got desired answer, just for better clarification for others I put my opinion here.
Reason :
It is happend due to context mismatch issue. Your passing context to Navigator.of(context).pop() is not matching with your MainApp BuildContext.
Solution : There has 2 way
U can use Global key
pass actual context to your Navigator
Below link I already mentioned how to solve this by passing actual context
https://stackoverflow.com/a/73543251/6109034
Try this:
Future<AlertDialog> myDialog(BuildContext context) {
return showDialog<AlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
margin: EdgeInsets.all(8.0),
child: Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Insira o número de telefone",
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(2.0)))),
),
],
),
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Cancelar")),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Aceitar"))
],
);
},
);
}
declare dialog and set in initState
late Dialog dialog;
#override
void initState() {
super.initState();
dialog = Dialog(
...
);
}
before calling a dialog when a page is just loading, call it by adding SchedulerBinding to it, call it like this
SchedulerBinding.instance?.addPostFrameCallback((_) => showDialog( context: context, barrierDismissible: false, builder: (context) { return dialogBox(context, "Fetching account data", 'Profile page', DialogType.processing, function: () {}, dismissText: "", ); }));
In my case I was using a provider where I used a context as an argument to a function, the thing was that when I passed that page I did it with pushnamedAndRemove Until then on the next page I was trying to use a function where I required the above context, so the error was mine because it was trying to get a parameter that I destroyed earlier, for that reason it didn't work. So be careful if you are deleting old pages.
Use this if You are using Stack in AlertDialog Not Closing on Navigator.of(context).pop();
late NavigatorState _navigator;
#override
void didChangeDependencies() {
_navigator = Navigator.of(context);
super.didChangeDependencies();
}
Use This
Positioned(right: 10.0,child: GestureDetector(
// behavior: HitTestBehavior.translucent,
onTap: () {
_navigator.pop(context);
},
child: Align(
alignment: Alignment.topRight,
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.white,
child: Icon(Icons.close, color: black),
),
),
),
),
I simply solved this by wrapping the showDialog with a Builder widget, though for me the error came from a stream builder I simply wrap the stream builder with a builder widget and the remove the notify listeners from the a stream am calling in the stream builder, but in your case wrap the showDialog with a Builder widget and it will use the context from the builder, problem solved
first : declare a FormKey.
GlobalKey<FormState>myFormKey=GlobalKey<FormState>();
second : add the FormKey to your Form widget.
Form(
key:myFormKey,
child:child
)
In my case i was calling
setState(() {
Navigator.pop(context);
});