Как сделать секундомер, снимающий виджет с эфира? - PullRequest
0 голосов
/ 28 мая 2020

Мне нужно знать, как сделать этот секундомер, который через 48 часов отключает виджет, который в моем случае является кнопкой. Может кто-нибудь объяснить мне, как это сделать? Какие классы использовать?

Я пытался использовать это, но не работает:

var timer = Timer(Duration(seconds: 1), () => print('done'));

1 Ответ

0 голосов
/ 29 мая 2020

мне кажется, что вы хотите, чтобы эта кнопка была отключена через 2 дня после установки приложения, вам нужно сохранить дату на устройстве, чтобы после перезапуска приложения дата была сама собой, вам нужно использовать package сохраняет данные на устройстве. Я рекомендую shared_preference, который прост в использовании.

для вашего случая, на экране, где вы используете кнопку, которая вам нужна для этого

import 'package:shared_preferences/shared_preferences.dart';

class MyFirstStatefullScreen extends StatefullWidget {
  MyFirstStatefullScreenState createState() => MyFirstStatefullScreenState();
}

class MyFirstStatefullScreenState extends State<MyFirstStatefullScreen>{
// some other code that u wrote 
  bool shouldButtonBeActive = true;

 @override
 void initState() {
    Future.delayed(Duration(0))
          .then((_) {
         SharedPreferences sharedPrefs= await SharedPreferences.getInstance();

         final deadLine = sharedPrefs.getString('deadLine');

         if(deadLine == null) {
           // this is the first time the app has been installed on the device
           // so we need to set the deadLine to N number of days after the installation

           final deadLineDate = DateTime.now().add(Duration(days: 2)); // 2 days from the date that the app was installed;


           sharedPrefs.setString(deadLineDate.toIso8601String()); // set it so we can check on the successfull state

          return;

         }

         final deadLineDate = DateTime.parse(deadLine); // since we stored it as a string;
          /// the deadline is set and is not null

         if(DateTime.now().compareTo(deadLineDate) == 0) {
          we are successfull, N hours have passed since the intial instalation, now we can disable the button

             shouldButtonBeActive = false; // the button should be disabled
         }

       })

 }

  Widget build(context) {

      // in your UI where you use the button 

       MaterialButton(
         child: Text("Button"),
         onPressed: shouldButtonBeActive ? func() : null
       )
   }
}

PS: мы используем Future внутри initState, потому что доза initState не позволяет asyn c (вызовы API, доступ к хранилищу) в нем.

...