I tried to ask the user, if he is sure to change the data after pressing on a dropdown menu.
Currently, I launch an alert dialog after onChanged. Asking the user "Are you sure to change data ?". If Yes , I save the data changes. If "No", I close the alert dialog.
But if user chooses "No", the data has been changed and I don't want to change the data... How can I stop the change? I have a complicated solution where I save all data change, and when the user presses NO, I load the last data save before "NO" but I found this to complicated. Are there any other, more simple solution ? Thank you
Here is my code :
new DropdownButton<String>(
onChanged: (String changedValue) {
dialog(); //lanche dialog with choice of data modification
data=changedValue;
setState(() {
data;
});
},
value: data,
items: <String>['data1', 'data2', 'data3','data4', 'data5']
.map((String changedValue) {
return new DropdownMenuItem<String>(
value: changedValue,
child: new Text(changedValue),
);
}).toList()),
You should update the setState data value in your decision function. Check the following code.
new DropdownButton<String>(
onChanged: (String changedValue) {
_showDialog(changedValue); // I changed this.
},
value: data,
items: <String>['data1', 'data2', 'data3', 'data4', 'data5']
.map((String changedValue) {
return new DropdownMenuItem<String>(
value: changedValue,
child: new Text(changedValue),
);
}).toList()),
void _showDialog(selection) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Alert Dialog title"),
content: new Text("Alert Dialog body"),
actions: <Widget>[
new FlatButton(
child: new Text("No"),
onPressed: () {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text("Yes"),
onPressed: () {
// this is where data value updates.
setState(() {
data = selection;
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
I know this is too late to answer this question since this question was asked almost 4 years back from now. But some one like me will come around this question I guess. Here is the answer for you guys.
We can just reset the value of a dropdown to its initial value by calling reset method on the key of the dropdown button's state key.
Declare a global key for DropDownButton widget in the state class of your widget or screen
final _dropDownKey = GlobalKey<FormFieldState>();
Attach the key in the constructor of your dropdown button
You can now call reset method from the current state of the dropdown key to reset the dropdown value to its initial value.
_dropDownKey.currentState?.reset();
in my case when the user taps "NO" in the confirmation dialog, I have to set the old value in the dropdown.
What I have done is I waited for the result from alert dialog by async/await (alert dialog returns a nullable bool). When the pop up is closed a boolean or null will be returned. I added a if statement to reset the dropdown value if alert dialog returns false or null (which means user tapped on "NO" button or user dismissed the dialog by tapping on the empty area).
Future<void> _showDropDownChangeConfirmAlert(BuildContext context, FBO? fbo){
......
final isChangeConfirmed = await AlertDialogUtils.showConfirmationDialog(
context,
title: title,
content: content,
onPrimaryActionPressed: () => widget.onFboSelected.call(fbo),
);
// If the user taps on No in the confirmation dialog
// Below code resets the dropdown value to the old selected FBO
if ((isChangeConfirmed ?? false) == false) {
if (mounted) {
_dropDownKey.currentState?.reset();
}
}
....
}
Ps: AlertDialogUtils is a class in my project. It won't works in your project. Copy the idea not the code :)
Related
I'm trying to implement App Tracking Transparency on my Flutter app with the package app_tracking_transparency 2.0.2+4 for iOS.
I'm on Flutter 3.0.5
Before the ATT dialog, I want show a custom dialog but my app show only the ATT dialog without my custom dialog before.
This is my code:
class _MyAppState extends State<MyApp> {
String _authStatus = 'Unknown';
Completer<ThemeData>? themeDataCompleter;
SharedPreferences? SharedPreferences;
#override
void initState() {
super.initState();
initPlugin();
}
Future<void> initPlugin() async {
final TrackingStatus status =
await AppTrackingTransparency.trackingAuthorizationStatus;
setState(() => _authStatus = '$status');
// If the system can show an authorization request dialog
if (status == TrackingStatus.notDetermined) {
// Show a custom explainer dialog before the system dialog
await showCustomTrackingDialog(context);
// Wait for dialog popping animation
await Future.delayed(const Duration(milliseconds: 2000), (){});
// Request system's tracking authorization dialog
final TrackingStatus status =
await AppTrackingTransparency.requestTrackingAuthorization();
setState(() => _authStatus = '$status');
}
final uuid = await AppTrackingTransparency.getAdvertisingIdentifier();
print("UUID: $uuid");
}
Future<void> showCustomTrackingDialog(BuildContext context) async =>
await showDialog<void>(
context: context,
builder: (context) =>
AlertDialog(
title: const Text('Dear User'),
content: const Text(
'We care about your privacy and data security. We keep this app free by showing ads. '
'Can we continue to use your data to tailor ads for you?\n\nYou can change your choice anytime in the app settings. '
'Our partners will collect data and use a unique identifier on your device to show you ads.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Continue'),
),
],
),
);
What is wrong?
I check the dev's example un pub.dev page but it seems the same code.
Thank you
I have a simple app with a CupertinoTabBar. It's almost like shown here: https://codesinsider.com/flutter-cupertino-tabbar/
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: [
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.home),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.person),
label: "Profile",
)
],
),
tabBuilder: (context, index) {
return CupertinoTabView(
builder: (context) {
return data[index];
},
);
},
)
On a Details Page, which is accessible from "Home" and "Profile" there is a Back Button which should lead back to the previous Main page (Profile or Home) (In the Details Page the CupertinoTabBar is not shown) But I'm struggling to achieve this. Any tips would be helpful. (On Android it was easy with defining named routes in the BottomNavigationBar and then just call Navigator.pushNamed)
I need a way to go to page with index 0 or index 1 manually. The CupertinoTabBar should appear again when back is pressed.
I have a widget named GiftGrid that shows a placeholder Text widget when it receives no items, but the test that checks for the specific case fails, even though it works fine in the app:
testWidgets('Null list shows placeholder', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
localizationsDelegates: [MyLocalizationsDelegate()],
home: GiftGrid(null)));
var a = tester.allWidgets.toList();
expect(find.text("PROPER_QUADRUPLE_CHECKED_STRING"), findsOneWidget);
});
where GiftGrid is defined as follows:
return (widget.giftList?.isEmpty ?? true)
? Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(MyLocalizations.of(context).stringThatTranslatesToSameAsTest),
),
) : StaggeredGridBuilder(...);
The debugger shows the contents of a as follows (sorry for the screenshot, I couldn't find a better way to show it):
EDIT: GifGrid receives a List as the parameter and the following test passes:
testWidgets('Gift shows thumbnail if available', (WidgetTester tester) async {
var gift = GiftModel()
..images = [
"OTHER_IMG_LINK"
]
..thumbnail =
"IMG_LINK";
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(
home: GiftGrid([gift]),
));
expect(find.byWidgetPredicate((widget) {
return widget is TransitionToImage &&
(widget.image as AdvancedNetworkImage).url ==
"IMG_LINK";
}), findsOneWidget);
});
I have a form that uses FocusNodes to visually indicate which part of the form is active. One field extends a PopupRoute as a kind of pop up 'keyboard'. My problem is, when I press that field, the keyboard pops up but the visual effect of the focus doesn't occur.
Some debugging from the FocusNode's listeners shows it gets focus but immediately loses it. I think it is because the new PopupRoute has a new FocusScopeNode, so my FocusNode doesn't have focus any more.
How can I keep the field focused while in the other route? I've tried:
Using FocusScope.of(context).reparentIfNeeded(focusNode) in all the build methods, which didn't do anything (I don't really understand this function tbh)
Passing the current FocusScope.of(context) into my custom PopupRoute to use. This actually worked, but after it's popped, I can't focus anything anymore (I guess it gets disposed?)
Code-wise, I'm calling requestFocus on the field tap, and adding this listener in initState:
widget.focusNode.addListener(() {
print(widget.focusNode);
if (widget.focusNode.hasFocus) {
Navigator.of(context).push(
CustomKeyboardPopupRoute(
state: widget.state,
position: //position stuff,
focusScopeNode: FocusScope.of(context), //the second of my ideas which didn't quite work above
)
).then((_) {
widget.focusNode.unfocus();
});
});
You are on the right track, indeed this happens because of the FocusScopeNode.
Make your keyboard route extend TransitionRoute:
class CustomKeyboardPopupRoute extends TransitionRoute {
#override
bool get opaque => false;
#override
Duration get transitionDuration => Duration(milliseconds: 300);
#override
Iterable<OverlayEntry> createOverlayEntries() sync* {
yield OverlayEntry(
opaque: false,
maintainState: true,
builder: _buildKeyboard,
);
}
Widget _buildKeyboard(BuildContext context) {
final positionAnimation = Tween(begin: Offset(0.0, 1.0), end: Offset.zero).animate(animation);
return SlideTransition(position: positionAnimation, child: Align(
alignment: Alignment.bottomCenter,
child: ...
),);
}
}
thanks very much.
Iterable<OverlayEntry> createOverlayEntries() sync* {
yield OverlayEntry(
opaque: false,
maintainState: true,
builder: (content) {
return ModalBarrier(dismissible: true);
}
);
yield OverlayEntry(
opaque: false,
maintainState: true,
builder: _buildContent,
);
}
I have a situation where I need to programmatically focus on a InputField(such as in response to a button press).
I'm using the Focus.moveTo function; however, even though the InputField is focused (blinking cursor appears) the keyboard is not brought up.
It seems like the best solution would be to call the RequestKeyboard() function in _InputFieldState, but this is private.
What would be the best way to accomplish this?
Here is a code sample showing the workflow:
class InputFieldWrapper extends StatefulWidget {
#override
_InputFieldWrapperState createState() => new _InputFieldWrapperState();
}
class _InputFieldWrapperState extends State<InputFieldWrapper> {
InputValue _currentInput = new InputValue(text: 'hello');
// GlobalKey for the InputField so we can focus on it
GlobalKey<EditableTextState> _inputKey = new GlobalKey<EditableTextState>();
#override
Widget build(BuildContext context) {
return new Column(
children: [
// Button that should focus on the InputField when pressed
new IconButton(
icon: new Icon(Icons.message),
onPressed: () {
Focus.moveTo(_inputKey);
},
),
// InputField that should be focused when pressing the Button
new InputField(
value: _currentInput,
key: _inputKey,
onChanged: (InputValue input) {
setState(() {
_currentInput = input;
});
}
),
],
);
}
}
This was decided to be a bug and is being tracked at #7985.