Need to close a Modal Bottom Sheet that contains a SimpleDialog flutter - dart

I need a way to close a Modal Bottom Sheet when an action is performed on the SimpleDialog, I have something like this:
Widget _getActionsMenu() {
return Container(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: IconButton(
icon: Icon(Icons.arrow_forward_ios),
color: Colors.grey[400],
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
leading: new Icon(Icons.train),
title: new Text(Utility.format(
Language.of(context).takePlace, [_place.title])),
onTap: () {
showUserStatusDialog<DialogActions>(
context: context,
child: this._getCurrentUserPlaceStatus());
},
),
new ListTile(
leading: new Icon(Icons.share),
title: new Text(Language.of(context).share),
onTap: () {
Share.share(Utility.format(
Language.of(context).placeInvitation,
[_place.title, 'GooglePlay']));
},
),
],
);
});
},
));
}
Widget _getCurrentUserPlaceStatus() {
//Here are an API call to get some data, we will name this variable as data
var data = getAPIData();
if (data == null) return null; //Also here I need a way to not show the modal and close the modal bottom sheet
return SimpleDialog(
title: Text(data['getCurrentUserPlaceStatus']['status'] == 2
? 'You are going to '
: 'You are in ' +
data['getCurrentUserPlaceStatus']['place']['name']),
children: <Widget>[
FlatButton(
child: Text(Language.of(context).no),
onPressed: () {
Navigator.pop(context, DialogActions.cancel);
}),
FlatButton(
child: Text(Language.of(context).yes),
onPressed: () {
Navigator.pop(context, DialogActions.agree);
})
],
);
}
void showUserStatusDialog<T>({BuildContext context, Widget child}) {
showDialog<T>(
context: context,
builder: (BuildContext context) => child,
).then<void>((T value) {
if (value != null) {
//Here I need to close the Modal Bottom
}
});
}
I need to close the modal bottom when an action is performed in the Simple Dialog, but also, when the return is null, I need to not display a simple modal(I mean just ignore the action) and close the modal bottom sheet.
I will appreciate any feedback.

Solution is just set Navigator.pop(context, DialogActions.cancel); in else case, and return Container();
And into showUserStatusDialog, into the then, use this Navigator.pop(context);

Related

Flutter PopupMenuButton onSelected not triggered

PopupMenuButton onSelected not getting called on iPhone 11, even when I add a breakpoint, and it's not working. When I click on the PopupMenuItem, the PopupMenuButton just disappears.
enum FeedMoreAction { Report, Block }
class UserInfoWidget extends StatefulWidget {
#override
_UserInfoWidgetState createState() => _UserInfoWidgetState();
}
class _UserInfoWidgetState extends State<UserInfoWidget> {
final GlobalKey _popupButtonKey = GlobalKey<State>();
final List<PopupMenuEntry> _menuEntries = [
PopupMenuItem<FeedMoreAction>(
value: FeedMoreAction.Report,
child: Text('Report'),
),
PopupMenuItem(
value: FeedMoreAction.Block,
child: Text('Block'),
),
];
#override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
PopupMenuButton<FeedMoreAction>(
onSelected: (FeedMoreAction action) async {
switch (action) {
case FeedMoreAction.Report:
showDialog(
context: context,
barrierDismissible: false,
child: AlertDialog(
title: Text('Are your sure?'),
content: Container(
height: 50,
child: Text('Are you sure you want to report this?')),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Yes')),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('No')),
],
));
break;
case FeedMoreAction.Block:
break;
default:
}
},
itemBuilder: (_) => _menuEntries,
key: _popupButtonKey,
child: GestureDetector(
onTap: () async {
// Here we get the render object of our physical button, later to get its size & position
final RenderBox popupButtonObject =
_popupButtonKey.currentContext.findRenderObject();
// Get the render object of the overlay used in `Navigator` / `MaterialApp`, i.e. screen size reference
final RenderBox overlay =
Overlay.of(context).context.findRenderObject();
// Calculate the show-up area for the dropdown using button's size & position based on the `overlay` used as the coordinate space.
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
popupButtonObject.localToGlobal(Offset.zero,
ancestor: overlay),
popupButtonObject.localToGlobal(
popupButtonObject.size.bottomRight(Offset.zero),
ancestor: overlay),
),
Offset.zero &
overlay
.size, // same as: new Rect.fromLTWH(0.0, 0.0, overlay.size.width, overlay.size.height)
);
await showMenu(
context: context, position: position, items: _menuEntries);
},
child: Icon(Icons.more_horiz_outlined),
),
),
],
);
}
}

AlertDialog setstate in Function/OnTap

new to flutter. I know how to set state the alert dialog, but with the need of tap to function like ()=> _createPlayer, It does not want to rebuild the alert dialog.
I wonder how to set state on alert dialog when you need to tap them.
File _image;
GestureDetector(
onTap: () => _createPlayer(),
After tap, it will display an alert dialog like this:
_createPlayer() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0))),
content: Container(
height: 400,
width: 300,
child: Column(
children: <Widget>[
Text('Create Player', style: Theme
.of(context)
.textTheme
.body1),
GestureDetector(
onTap: _getImageCamera,
child: CircleAvatar(
radius: 100,
backgroundColor: Colors.white,
backgroundImage: _image != null ? FileImage(_image) : AssetImage('assets/images/undercover.png'),
),
),
],
),
),
);
});
}
_getImageCamera() async{
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
I want to set state/change the image in alert dialog when selected. Any idea?
You can use StatefulBuilder for change inside dialog
showDialog(
context: context,
builder: (context) {
String contentText = "Content of Dialog";
// add StatefulBuilder to return value
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text("Title of Dialog"),
content: Text(contentText),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text("Cancel"),
),
FlatButton(
onPressed: () {
setState(() {
contentText = "Changed Content of Dialog";
});
},
child: Text("Change"),
),
],
);
},
);
},
);
Create a separate Stateful Widget CustomDialog for the AlertDialog and move the _getImageCamera function _image variable inside it like this
_createPlayer() {
return CustomDialog();
}
class CustomDialog extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return CustomDialogState();
}
}
class CustomDialogState extends State<CustomDialog> {
ImageProvider _image;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0))),
content: Container(
height: 400,
width: 300,
child: Column(
children: <Widget>[
Text('Create Player', style: Theme
.of(context)
.textTheme
.body1),
GestureDetector(
onTap: _getImageCamera,
child: CircleAvatar(
radius: 100,
backgroundColor: Colors.white,
backgroundImage: _image != null ? FileImage(_image) : AssetImage('assets/images/undercover.png'),
),
),
],
),
),
);
});
}
_getImageCamera() async{
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
}
In order to see UI changes on showDialog, you have to create a new StatefulWidget and then work with dialog in that class. Here is the example/sample code
The most stupidest and quickest fix is:
Navigator.of(context).pop();
Then call the showDialog() again.
There will be a micro delay but works.

Show snackbar when item is tapped in bottom sheet

I want to show Snackbar when an item is clicked in the bottom sheet. I tried this.
#override
Widget build(BuildContext defaultContext) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () => showModalBottomSheet(
context: defaultContext,
builder: (BuildContext context) {
return Builder(
builder: (BuildContext builderContext) {
return ListTile(
title: Text("Click me"),
onTap: () {
Navigator.pop(builderContext); // hiding bottom sheet
Scaffold.of(builderContext).showSnackBar(SnackBar(content: Text("Hi")));
},
);
},
);
},
),
),
),
);
}
But I am having error
Scaffold.of() called with a context that does not contain a Scaffold
Note The question is not a duplicate of this
PS: I know I can use GlobalKey in Scaffold to show the Snackbar but I want to do it using Builder like the docs suggest to use Builder. I did use builder and it didn't work.
This worked out finally.
#override
Widget build(BuildContext defaultContext) {
return Scaffold(
body: Center(
child: Builder(builder: (builderContext) {
return RaisedButton(
onPressed: () => showModalBottomSheet(
context: defaultContext,
builder: (BuildContext context) {
return ListTile(
title: Text("Click me"),
onTap: () {
Navigator.pop(builderContext); // hiding bottom sheet
Scaffold.of(builderContext).showSnackBar(SnackBar(content: Text("Hi")));
},
);
},
),
);
},),
),
);
}
I need to move Builder up the tree. Don't know the reason why but it worked.

Change Variable values in Flutter

I'm trying to change some variables in different methos in Flutter, but the value isn't changed.
An example is something like:
enum UserPlaceStatusType { NONE, GOING, THERE, OUT, CANCELLED }
class PlaceCardState extends State<PlaceCard> {
UserPlaceStatusType _isOtherPlaceActive = UserPlaceStatusType.NONE;
Widget build(BuildContext context) {
return Card(
child: Scaffold(
body: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this._getBody(),
),
bottomNavigationBar: this._getBottomNavigationBar()));
}
List<Widget> _getBody() {
return [
Expanded(child: Text('test'), flex: 3),
Expanded(child: Text('test'), flex: 6),
Expanded(child: this._getActionsMenu(), flex: 1)
];
}
Widget _getActionsMenu() {
return Container(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: IconButton(
icon: Icon(Icons.arrow_forward_ios),
color: Colors.grey[400],
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
leading: new Icon(Icons.train),
title: new Text(Utility.format(
Language.of(context).takePlace, [_place.title])),
onTap: () {
showUserStatusDialog<DialogActions>(
context: context,
//It opens a simple dialog
child: this._getCurrentUserPlaceStatus());
},
),
],
);
});
},
));
}
Widget _getCurrentUserPlaceStatus() {
return new GraphqlProvider(
client: new ValueNotifier(
Client(endPoint: 'GraphQLUrl', cache: new InMemoryCache()),
),
child: new Query(
'The GraphQL Query',
variables: {},
builder: ({
bool loading,
var data,
var error,
}) {
if (data != null && data['getCurrentUserPlaceStatus'] != null) {
this._isOtherPlaceActive = UserPlaceStatusType.THERE;
Navigator.pop(context, DialogActions.cancel);
return Container();
} else {
this._isOtherPlaceActive = UserPlaceStatusType.GOING;
Navigator.pop(context, DialogActions.cancel);
return Container();
}
},
));
}
void showUserStatusDialog<T>({BuildContext context, Widget child}) async {
//here there is a validation but the variable value is the initial one, I mean NONE
if (this._isOtherPlaceActive == UserPlaceStatusType.GOING) {
//Cod to do
return;
}
showDialog<T>(
context: context,
builder: (BuildContext context) => child,
).then<void>((T value) {
if (value != null) {
this._isOtherPlaceActive = UserPlaceStatusType.NONE;
Navigator.pop(context);
}
});
}
}
I changed the variable value through some methods, but when I need to apply the validation, that's the initial value, it isn't changed, and I could not apply SetState method cuz it breaks the modal and throws an exception.
I will appreciate any feedback.
The method setState() can't be called inside a widget directly. I'm curious with your use of GrapQLProvider since it returns an empty Container() widget just to check the status of the data.
While I'm unfamiliar with the use of GraphQL, if the client that you're using inherits either a Stream or Future, it can be used to listen when the query is done.
Here's some snippets as demo. Let _testFuture() as the sample for a Future callback.
Future _testFuture() async{
return null;
}
Future can be listened to inside a Widget. When the request finishes, we have the opportunity to call setState().
_testFuture().then((value) {
// Check for values here
setState(() {
// Update values
});
});
Or if the request is set in a Stream, it's also possible to listen for Stream changes inside a Widget.
_streamController.add(_testFuture());
_streamController.stream.listen((event) {
// Check for values here
setState(() {
// Update values
});
});
This may not be the exact answer that you're looking for, but I hope this can guide you for a solution to your approach. I also found a GraphQL sample that uses ObservableQuery as a Stream that you can try.
Your code is very complex and should be refactored. Please notice how dialogs must be called.
enum DialogResult {ok, cancel}
caller_widget.dart
FlatButton(
child: Text('Open dialog'),
onPressed: () async {
// Call dialog and wait for result (async call)
final dialogResult = await showDialog<DialogResult>(
context: context,
builder: (context) => DialogWidget(),
);
if (dialogResult == DialogResult.ok) {
// do something
}
},
),
dialog_widget.dart
...
FlatButton(
child: Text('Ok'),
onPressed: () => Navigator.pop(context, DialogResult.ok), // DialogResult.ok returns
),
FlatButton(
child: Text('Cancel'),
OnPressed: () => Navigator.pop(context, DialogResult.cancel), // DialogResult.cancel returns
),
So you can return required value from dialog and set it to required variable.
P.S. Try to avoid use of old fashion then process of futures and use async/await.

Destruct and Construct cards in Flutter dynamically

I'm new to Flutter,
I want to destruct cards created initially and construct them again as per data provided in API call.
Basically when I tap on button in UI, it should call APIs and based on data from API call, if it is different from the data I already have, I want to destruct cards and construct them again.
How I can achieve this?
The cards will auto update their content when you make the call again, it is like refreshing your data.
I have made a simple example with a single card that shows data from this JSON Where I am calling the API first time in initState and then repeating the call each time I press on the FAB.
I am adding the index variable just to show you the updates (updating my single card with the next item in the list)
Also it is worth noting that I am handling the null or empty values poorly for the sake of time.
Also forget about the UI overflow ¯_(ツ)_/¯
class CardListExample extends StatefulWidget {
#override
_CardListExampleState createState() => new _CardListExampleState();
}
class _CardListExampleState extends State<CardListExample> {
Map cardList = {};
int index = 0;
#override
void initState() {
_getRequests();
super.initState();
}
_getRequests() async {
String url = "https://jsonplaceholder.typicode.com/users";
var httpClinet = createHttpClient();
var response = await httpClinet.get(
url,
);
var data = JSON.decode(response.body);
//print (data);
setState(() {
this.cardList = data[index];
this.index++;
});
print(cardList);
print(cardList["name"]);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton:
new FloatingActionButton(onPressed: () => _getRequests()),
appBar: new AppBar(
title: new Text("Card List Example"),
),
body: this.cardList != {}
? new ListView(children: <Widget>[
new Card(
child: new Column(
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Text(
cardList["name"] ?? '',
style: Theme.of(context).textTheme.display1,
),
new Text(
this.cardList['email'] ?? '',
maxLines: 50,
),
],
),
new Text(cardList["website"] ?? '')
],
),
),
])
: new Center(child: new CircularProgressIndicator()),
);
}
}
Yes, Answer from Aziza works.
Though I used the code as below :
void main() =>
runApp(new MaterialApp(
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/about':
return new FromRightToLeft(
builder: (_) => new _aboutPage.About(),
settings: settings,
);
}
},
home : new HomePage(),
theme: new ThemeData(
fontFamily: 'Poppins',
primarySwatch: Colors.blue,
),
));
class HomePage extends StatefulWidget{
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage>{
List data;
Future<String> getData() async{
var response = await http.get(
Uri.encodeFull(<SOMEURL>),
headers: {
"Accept" : "application/json"
}
);
this.setState((){
data = JSON.decode(response.body);
});
return "Success";
}
#override
void initState() {
// TODO: implement initState
super.initState();
this.getData();
}
#override
Widget build(BuildContext context){
return new Scaffold(
appBar : new AppBar(
title : new Text("ABC API"),
actions: <Widget>[
new IconButton( // action button
icon: new Icon(Icons.cached),
onPressed: () => getData(),
)],
),
drawer: new Drawer(
child: new ListView(
children: <Widget> [
new Container(
height: 120.0,
child: new DrawerHeader(
padding: new EdgeInsets.all(0.0),
decoration: new BoxDecoration(
color: new Color(0xFFECEFF1),
),
child: new Center(
child: new FlutterLogo(
colors: Colors.blueGrey,
size: 54.0,
),
),
),
),
new ListTile(
leading: new Icon(Icons.chat),
title: new Text('Support'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/support');
}
),
new ListTile(
leading: new Icon(Icons.info),
title: new Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/about');
}
),
new Divider(),
new ListTile(
leading: new Icon(Icons.exit_to_app),
title: new Text('Sign Out'),
onTap: () {
Navigator.pop(context);
}
),
],
)
),
body: this.data != null ?
new ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index){
return new Container(
padding: new EdgeInsets.fromLTRB(8.0,5.0,8.0,0.0),
child: new Card(
child: new Padding(
padding: new EdgeInsets.fromLTRB(10.0,12.0,8.0,0.0),
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
enabled: data[index]['active'] == '1' ? true : false,
title: new Text(data[index]['header'],
style:Theme.of(context).textTheme.headline,
),
subtitle: new Text("\n" + data[index]['description']),
),
new ButtonTheme.bar(
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: new Text(data[index]['action1']),
onPressed: data[index]['active'] == '1' ? _launchURL :null,
),
],
),
),
],
),
),
),
);
},
)
:new Center(child: new CircularProgressIndicator()),
);
}
}
_launchURL() async {
const url = 'http://archive.org';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
class FromRightToLeft<T> extends MaterialPageRoute<T> {
FromRightToLeft({ WidgetBuilder builder, RouteSettings settings })
: super(builder: builder, settings: settings);
#override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
if (settings.isInitialRoute)
return child;
return new SlideTransition(
child: new Container(
decoration: new BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.black26,
blurRadius: 25.0,
)
]
),
child: child,
),
position: new Tween(
begin: const Offset(1.0, 0.0),
end: const Offset(0.0, 0.0),
)
.animate(
new CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
)
),
);
}
#override Duration get transitionDuration => const Duration(milliseconds: 400);
}
The above code includes Navigation drawer, page navigation animation and also answer to the above question.

Resources