在flutter中的另一天开始时从sharedpreferences中删除存储的数据

vuktfyat  于 2023-01-31  发布在  Flutter
关注(0)|答案(1)|浏览(127)

我有一个应用程序我正在工作。我用sharedpreferences和提供程序来存储屏幕的页面浏览量的索引,以便当我点击主页上的按钮时,它会导航到页面浏览屏幕,并将继续从页面浏览屏幕的最后一个索引页我离开应用程序之前。但是,我想使应用程序从第一个索引开始,如果日期更改为另一个日期。
为了进一步解释,如果用户在早上打开应用程序1月28日,我希望在离开应用程序之前存储他们上一页的索引。如果用户在下午回来,我希望他们从停止的地方继续。但是,如果时间从上午12点整更改为1月29日,我想清除保存在sharedpreferences中的数据,以便它们可以从第一个索引开始。
我知道我将使用sharedpreference清除或删除方法,但我不知道如何每天跟踪,以便我可以使用该方法。
我已经创建了保存最后一个索引的代码,但仍然保留了如何为每次日期更改清除最后一个索引。
这是我的提供程序和共享首选项文件

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ProviderData extends ChangeNotifier {
  SharedPreferences? prefs;
  final String pageIndexKey = 'pageIndex';
  int? _pageIndex;

  ProviderData() {
    _pageIndex = 0;
    loadFromPrefs();
  }

  _initPrefs() async {
    prefs ??= await SharedPreferences.getInstance();
  }

  loadFromPrefs() async {
    await _initPrefs();
    _pageIndex = prefs!.getInt(pageIndexKey) ?? 0;
    notifyListeners();
    return _pageIndex;
  }

  _savePageIndexToPrefs({required String key, required int value}) async {
    await _initPrefs();
    prefs!.setInt(key, value);
  }

  void changePageIndex(int newPageIndex) {
    _pageIndex = newPageIndex;

    _savePageIndexToPrefs(key: pageIndexKey, value: _pageIndex!);
    notifyListeners();
  }
}

下面是我的PageViewScreen文件,
我使用Future Builder获取我的最后一个索引,以便基于最后一个索引构建我的应用程序

Future getProvider() {
 return ProviderData().loadFromPrefs().then((value) {
   return PageController(initialPage: value - 1);
 });
}

@override
Widget build(BuildContext context) {
 return Scaffold(
     body: FutureBuilder(
         future: getProvider(),
         builder: ((context, snapshot) {
           if (snapshot.connectionState == ConnectionState.done) {
             if (snapshot.hasError) {
               return Center(
                   child: Text(
                 '${snapshot.error} occurred',
                 style: TextStyle(fontSize: 18),
               ));
             } else if (snapshot.hasData) {
               final control = snapshot.data;

               return Stack(
                 children: [
                   Consumer<ProviderData>(
                     builder: (context, providerData, _) {
                       return PageView(
                         controller: control,
                         onPageChanged: (index) {

           ///// I saved the index of the pageview here but I would love to clear it and make it start from index1 for every new date i.e 12am of everyday.

                           providerData.changePageIndex(index);

                           // setState(() {
                           //   onLastPage = index == 2;
                           //   onFirstPage = index == 0;
                           //   onSecondPage = index == 1;
                           //   onThirdPage = index == 2;
                           //   onFourthPage = index == 3;
                           //   onFifthPage = index == 4;
                           //   onSixthPage = index == 5;
                           //   onSeventhPage = index == 6;
                           // });
                         },
                         children: _pageList,
                       );
                     },
                   ),
                   Align(
                     alignment: Alignment(0, -0.8),
                     child: Consumer<ProviderData>(
                         builder: (context, providerData, _) {
                       return SmoothPageIndicator(
                         controller: control,
                         count: 13,
                         effect: SlideEffect(
                             activeDotColor: Color.fromRGBO(215, 60, 16, 1)),
                       );
                     }),
                   ),
                   Align(
                     alignment: Alignment(0, 0.5),
                     child: Row(
                       mainAxisAlignment: MainAxisAlignment.spaceAround,
                       children: [
                         GestureDetector(
                           onTap: (() {
                             control.previousPage(
                                 duration: Duration(milliseconds: 500),
                                 curve: Curves.easeIn);
                           }),
                           child: Text(
                             "prev",
                             style: TextStyle(
                                 fontWeight: FontWeight.w600, fontSize: 16),
                           ),
                         ),
                         GestureDetector(
                           onTap: (() {
                             control.nextPage(
                                 curve: Curves.easeIn,
                                 duration: Duration(milliseconds: 500));
                           }),
                           child: Text(
                             "Next",
                             style: TextStyle(
                                 fontWeight: FontWeight.w600, fontSize: 16),
                           ),
                         ),
                       ],
                     ),
                   )
                 ],
               );
             }
           }
           return Center(child: CircularProgressIndicator());
         }
         )
         )
         );
}

请我需要有人可以帮助我解决和处理这个问题。
先谢谢你

ql3eal8s

ql3eal8s1#

您可以将上次更改的日期保留在"共享偏好设置"中,并在每次加载偏好设置时检查它。保留不带时间和分钟的日期非常重要,因此在同一天重新创建日期将具有相同的值。
您可以简化提供程序逻辑,仅将其用作Provider,而不是ChangeNotifier。
下面是一个工作示例:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final sharedPrefs = await SharedPreferences.getInstance();
  runApp(
    Provider(
      create: (context) => ProviderData(sharedPrefs),
      child: const MainApp(),
    ),
  );
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  final _pages = [
    const Center(
      child: Text(
        'Page 1',
        style: TextStyle(fontSize: 38),
      ),
    ),
    const Center(
      child: Text(
        'Page 2',
        style: TextStyle(fontSize: 38),
      ),
    ),
    const Center(
      child: Text(
        'Page 3',
        style: TextStyle(fontSize: 38),
      ),
    ),
    const Center(
      child: Text(
        'Page 4',
        style: TextStyle(fontSize: 38),
      ),
    ),
  ];
  late final PageController _pageController;
  late final ProviderData _providerData;
  bool loading = true;

  @override
  void initState() {
    WidgetsBinding.instance.scheduleFrameCallback((timeStamp) {
      _providerData = context.read<ProviderData>();
      _pageController = PageController(initialPage: _providerData.getPageIndex());
      setState(() => loading = false);
    });
    super.initState();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: loading
          ? const Center(child: CircularProgressIndicator())
          : Scaffold(
              body: Stack(
                children: [
                  PageView(
                    controller: _pageController,
                    children: _pages,
                    onPageChanged: (value) => _providerData.savePageIndexToPrefs(value: value),
                  ),
                  Align(
                    alignment: const Alignment(0, -0.8),
                    child: SmoothPageIndicator(
                      controller: _pageController,
                      count: _pages.length,
                      effect: const SlideEffect(activeDotColor: Color.fromRGBO(215, 60, 16, 1)),
                    ),
                  ),
                  Align(
                    alignment: const Alignment(0, 0.5),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        GestureDetector(
                          onTap: (() {
                            _pageController.previousPage(duration: const Duration(milliseconds: 500), curve: Curves.easeIn);
                          }),
                          child: const Text(
                            "Prev",
                            style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16),
                          ),
                        ),
                        GestureDetector(
                          onTap: (() {
                            _pageController.nextPage(curve: Curves.easeIn, duration: const Duration(milliseconds: 500));
                          }),
                          child: const Text(
                            "Next",
                            style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
    );
  }
}

class ProviderData {
  ProviderData(this._prefs);

  final SharedPreferences _prefs;
  static const String _pageIndexKey = 'pageIndex';
  static const String _pageIndexLastUpdated = 'pageIndexLastUpdatedKey';

  int getPageIndex() {
    final lastUpdatedStr = _prefs.getString(_pageIndexLastUpdated);
    if (lastUpdatedStr != null) {
      final lastUpdated = DateTime.parse(lastUpdatedStr);
      final now = DateTime.now();
      // creating a date without hours and minutes
      final today = DateTime.utc(now.year, now.month, now.day);
      if (lastUpdated.isAtSameMomentAs(today)) {
        final pageIndex = _prefs.getInt(_pageIndexKey) ?? 0;

        return pageIndex;
      }
    }

    _prefs.remove(_pageIndexKey);

    return 0;
  }

  void savePageIndexToPrefs({required int value}) {
    _prefs.setInt(_pageIndexKey, value);
    final now = DateTime.now();
    // creating a date without hours and minutes
    final today = DateTime.utc(now.year, now.month, now.day);
    _prefs.setString(_pageIndexLastUpdated, today.toIso8601String());
  }
}

相关问题