Browse Source

made futures acceptable as value in ToggleSwitchWidget

ashilkn 2 năm trước cách đây
mục cha
commit
bf0971f8ce

+ 11 - 6
lib/ui/backup_settings_screen.dart

@@ -56,8 +56,10 @@ class BackupSettingsScreen extends StatelessWidget {
                               menuItemColor: colorScheme.fillFaint,
                               trailingSwitch: ToggleSwitchWidget(
                                 value: () {
-                                  return Configuration.instance
-                                      .shouldBackupOverMobileData();
+                                  return Future.value(
+                                    Configuration.instance
+                                        .shouldBackupOverMobileData(),
+                                  );
                                 },
                                 onChanged: () async {
                                   await Configuration.instance
@@ -82,8 +84,9 @@ class BackupSettingsScreen extends StatelessWidget {
                               ),
                               menuItemColor: colorScheme.fillFaint,
                               trailingSwitch: ToggleSwitchWidget(
-                                value: () =>
-                                    Configuration.instance.shouldBackupVideos(),
+                                value: () => Future.value(
+                                  Configuration.instance.shouldBackupVideos(),
+                                ),
                                 onChanged: () => Configuration.instance
                                     .setShouldBackupVideos(
                                   !Configuration.instance.shouldBackupVideos(),
@@ -107,8 +110,10 @@ class BackupSettingsScreen extends StatelessWidget {
                                     ),
                                     menuItemColor: colorScheme.fillFaint,
                                     trailingSwitch: ToggleSwitchWidget(
-                                      value: () => Configuration.instance
-                                          .shouldKeepDeviceAwake(),
+                                      value: () => Future.value(
+                                        Configuration.instance
+                                            .shouldKeepDeviceAwake(),
+                                      ),
                                       onChanged: () {
                                         return Configuration.instance
                                             .setShouldKeepDeviceAwake(

+ 75 - 62
lib/ui/components/toggle_switch_widget.dart

@@ -10,10 +10,10 @@ enum ExecutionState {
 }
 
 typedef OnChangedCallBack = Future<void> Function();
-typedef ValueCallBack = bool Function();
+typedef FutureValueCallBack = Future<bool> Function();
 
 class ToggleSwitchWidget extends StatefulWidget {
-  final ValueCallBack value;
+  final FutureValueCallBack value;
   final OnChangedCallBack onChanged;
   const ToggleSwitchWidget({
     required this.value,
@@ -26,12 +26,15 @@ class ToggleSwitchWidget extends StatefulWidget {
 }
 
 class _ToggleSwitchWidgetState extends State<ToggleSwitchWidget> {
+  late Future<bool> futureToggleValue;
   late bool toggleValue;
   ExecutionState executionState = ExecutionState.idle;
   final _debouncer = Debouncer(const Duration(milliseconds: 300));
   @override
   void initState() {
-    toggleValue = widget.value.call();
+    futureToggleValue = widget.value.call();
+//need to assign correct intiial value of toggleValue here
+    toggleValue = true;
     super.initState();
   }
 
@@ -40,68 +43,78 @@ class _ToggleSwitchWidgetState extends State<ToggleSwitchWidget> {
     final enteColorScheme = Theme.of(context).colorScheme.enteTheme.colorScheme;
     final Widget stateIcon = _stateIcon(enteColorScheme);
 
-    return Row(
-      children: [
-        Padding(
-          padding: const EdgeInsets.only(right: 2),
-          child: AnimatedSwitcher(
-            duration: const Duration(milliseconds: 175),
-            switchInCurve: Curves.easeInExpo,
-            switchOutCurve: Curves.easeOutExpo,
-            child: stateIcon,
-          ),
-        ),
-        SizedBox(
-          height: 31,
-          child: FittedBox(
-            fit: BoxFit.contain,
-            child: Switch.adaptive(
-              activeColor: enteColorScheme.primary400,
-              inactiveTrackColor: enteColorScheme.fillMuted,
-              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
-              value: toggleValue,
-              onChanged: (negationOfToggleValue) async {
-                setState(() {
-                  toggleValue = negationOfToggleValue;
-                  //start showing inProgress statu icons if toggle takes more than debounce time
-                  _debouncer.run(
-                    () => Future(
-                      () {
-                        setState(() {
-                          executionState = ExecutionState.inProgress;
-                        });
-                      },
-                    ),
-                  );
-                });
-                final Stopwatch stopwatch = Stopwatch()..start();
-                await widget.onChanged.call();
-                //for toggle feedback on short unsuccessful onChanged
-                await _feedbackOnUnsuccessfulToggle(stopwatch);
-                //debouncer gets canceled if onChanged takes less than debounce time
-                _debouncer.cancelDebounce();
-                setState(() {
-                  final newValue = widget.value.call();
-                  //if onchanged on toggle is successful
-                  if (toggleValue == newValue) {
-                    if (executionState == ExecutionState.inProgress) {
-                      executionState = ExecutionState.successful;
-                      Future.delayed(const Duration(seconds: 2), () {
-                        setState(() {
+    return FutureBuilder(
+      future: futureToggleValue,
+      builder: (context, snapshot) {
+        return Row(
+          children: [
+            Padding(
+              padding: const EdgeInsets.only(right: 2),
+              child: AnimatedSwitcher(
+                duration: const Duration(milliseconds: 175),
+                switchInCurve: Curves.easeInExpo,
+                switchOutCurve: Curves.easeOutExpo,
+                child: stateIcon,
+              ),
+            ),
+            SizedBox(
+              height: 31,
+              child: FittedBox(
+                fit: BoxFit.contain,
+                child: Switch.adaptive(
+                  activeColor: enteColorScheme.primary400,
+                  inactiveTrackColor: enteColorScheme.fillMuted,
+                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+                  value: toggleValue,
+                  onChanged: (negationOfToggleValue) async {
+                    setState(() {
+                      toggleValue = negationOfToggleValue;
+                      //start showing inProgress statu icons if toggle takes more than debounce time
+                      _debouncer.run(
+                        () => Future(
+                          () {
+                            setState(() {
+                              executionState = ExecutionState.inProgress;
+                            });
+                          },
+                        ),
+                      );
+                    });
+                    final Stopwatch stopwatch = Stopwatch()..start();
+                    await widget.onChanged.call();
+                    //for toggle feedback on short unsuccessful onChanged
+                    await _feedbackOnUnsuccessfulToggle(stopwatch);
+                    //debouncer gets canceled if onChanged takes less than debounce time
+                    _debouncer.cancelDebounce();
+
+                    widget.value.call().then((newValue) {
+                      setState(() {
+                        //if onchanged on toggle is successful
+                        // print('here');
+                        // print(toggleValue);
+                        // print("newValue : $newValue");
+                        if (toggleValue == newValue) {
+                          if (executionState == ExecutionState.inProgress) {
+                            executionState = ExecutionState.successful;
+                            Future.delayed(const Duration(seconds: 2), () {
+                              setState(() {
+                                executionState = ExecutionState.idle;
+                              });
+                            });
+                          }
+                        } else {
+                          toggleValue = !toggleValue;
                           executionState = ExecutionState.idle;
-                        });
+                        }
                       });
-                    }
-                  } else {
-                    toggleValue = !toggleValue;
-                    executionState = ExecutionState.idle;
-                  }
-                });
-              },
+                    });
+                  },
+                ),
+              ),
             ),
-          ),
-        ),
-      ],
+          ],
+        );
+      },
     );
   }
 

+ 26 - 35
lib/ui/settings/security_section_widget.dart

@@ -13,7 +13,6 @@ import 'package:photos/services/local_authentication_service.dart';
 import 'package:photos/services/user_service.dart';
 import 'package:photos/theme/ente_theme.dart';
 import 'package:photos/ui/account/sessions_page.dart';
-import 'package:photos/ui/common/loading_widget.dart';
 import 'package:photos/ui/components/captioned_text_widget.dart';
 import 'package:photos/ui/components/expandable_menu_item_widget.dart';
 import 'package:photos/ui/components/menu_item_widget.dart';
@@ -64,38 +63,30 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
       children.addAll(
         [
           sectionOptionSpacing,
-          FutureBuilder(
-            future: UserService.instance.fetchTwoFactorStatus(),
-            builder: (_, snapshot) {
-              return MenuItemWidget(
-                captionedTextWidget: const CaptionedTextWidget(
-                  title: "Two-factor",
-                ),
-                trailingSwitch: snapshot.hasData
-                    ? ToggleSwitchWidget(
-                        value: () => snapshot.data,
-                        onChanged: () async {
-                          final hasAuthenticated =
-                              await LocalAuthenticationService.instance
-                                  .requestLocalAuthentication(
-                            context,
-                            "Please authenticate to configure two-factor authentication",
-                          );
-                          if (hasAuthenticated) {
-                            if (!snapshot.data) {
-                              await UserService.instance
-                                  .setupTwoFactor(context);
-                            } else {
-                              _disableTwoFactor();
-                            }
-                          }
-                        },
-                      )
-                    : snapshot.hasError
-                        ? const Icon(Icons.error_outline_outlined)
-                        : const EnteLoadingWidget(),
-              );
-            },
+          MenuItemWidget(
+            captionedTextWidget: const CaptionedTextWidget(
+              title: "Two-factor",
+            ),
+            trailingSwitch: ToggleSwitchWidget(
+              value: () => UserService.instance.fetchTwoFactorStatus(),
+              onChanged: () async {
+                final hasAuthenticated = await LocalAuthenticationService
+                    .instance
+                    .requestLocalAuthentication(
+                  context,
+                  "Please authenticate to configure two-factor authentication",
+                );
+                final isTwoFactorEnabled =
+                    await UserService.instance.fetchTwoFactorStatus();
+                if (hasAuthenticated) {
+                  if (isTwoFactorEnabled) {
+                    _disableTwoFactor();
+                  } else {
+                    await UserService.instance.setupTwoFactor(context);
+                  }
+                }
+              },
+            ),
           ),
           sectionOptionSpacing,
         ],
@@ -107,7 +98,7 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
           title: "Lockscreen",
         ),
         trailingSwitch: ToggleSwitchWidget(
-          value: () => _config.shouldShowLockScreen(),
+          value: () => Future.value(_config.shouldShowLockScreen()),
           onChanged: () async {
             await LocalAuthenticationService.instance
                 .requestLocalAuthForLockScreen(
@@ -129,7 +120,7 @@ class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
               title: "Hide from recents",
             ),
             trailingSwitch: ToggleSwitchWidget(
-              value: () => _config.shouldHideFromRecents(),
+              value: () => Future.value(_config.shouldHideFromRecents()),
               onChanged: _hideFromRecentsOnChanged,
             ),
           ),