如何在Dart中每24小时更改一次文本

时间:2019-09-02 03:30:25

标签: android flutter dart

因此,基本上,我正在创建一个应用程序,该应用程序的主页上有一个“每日报价”。我已经在容器中添加了报价,但我无法每24小时更改一次报价。

我是Dart的新手,但是利用以前在其他编程语言上的知识,我认为我需要使用if-else语句,该语句也使用设备的内部时钟。我当时想这应该是“ If(0:00 AM){在数组中显示下一个引号} else {什么也不做}”。

import 'dart:async';

void main () => runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.red),
      home: MainActivity(),
    );
  }
}

class MainActivity extends StatefulWidget {
  @override
  _MainActivityState createState() => _MainActivityState();
}

class _MainActivityState extends State<MainActivity>
{
  String _timeString;

  @override
  void initState(){
    _timeString = "${DateTime.now().hour} : ${DateTime.now().minute}";
    Timer.periodic(Duration(seconds:1), (Timer t)=>_getCurrentTime());
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: new BoxDecoration(
              image: new DecorationImage(
                image: new AssetImage('assets/Day.png'),
                fit: BoxFit.cover,
              ),
            ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
          new Center(
            child:new Container(
              width: 200.0,
              height: 100.0,
              decoration: new BoxDecoration(
                shape: BoxShape.rectangle,
                color: Colors.white.withOpacity(0.7),
                borderRadius: new BorderRadius.circular(10.0),
                boxShadow: [
                  new BoxShadow(
                    color: Colors.black26,
                    offset: new Offset(5.0, 5.0),
                    blurRadius: 5.0
                  ),
                ]
              ),
            child: new Center(
              child: new Text(
                _timeString,
                style: new TextStyle(
                  color: Colors.white,
                  fontFamily: 'Open Sans',
                  fontSize: 50
                ),
              ),
            ),
            ),
          ),
          SizedBox(height: 300),           
          new Container(
              width: 345.0,
              height: 120.0,
              decoration: new BoxDecoration(
                shape: BoxShape.rectangle,
                color: Colors.white.withOpacity(0.7),
                borderRadius: new BorderRadius.circular(10.0),
                boxShadow: [
                  new BoxShadow(
                    color: Colors.black26,
                    offset: new Offset(5.0, 5.0),
                    blurRadius: 5.0
                  ),
                ]
              ),
            child: new Center(
              child: new Text(
                '“Morning is an important time of day, because how you spend your morning can often tell you what kind of day you are going to have.”\n\t ― Lemony Snicket, The Blank Book',
                style: new TextStyle(
                  color: Colors.white,
                  fontFamily: 'Playfair Display'
                ),
              ),
            ),
            ),
            ],
          ),
        ),
      ),
    );
  }

 void _getCurrentTime()  {
    setState(() {
  _timeString = "${DateTime.now().hour} : ${DateTime.now().minute}";
    });
  } 
}

无论我尝试多少次,这种方法都行不通,但这可能是由于我的知识有限。任何信息都会有所帮助。

2 个答案:

答案 0 :(得分:1)

使用2个变量。

一个用于存储用户进入应用程序时的上一个时间戳,另一个用于存储当前时间戳。完成以下条件的检查后,设置上一个时间戳记的值。

如果两个时间戳的两天不同,则请求随机报价。

如果您担心用户可能会玩手机,请使用SharePreferences在本地存储以前的报价。

如果您希望每天显示特定的报价,则存储每个报价的键对或索引对或日期-报价对对的值,如果它等于旧索引/存储在用户手机中的键/日期值,然后不要求输入新的报价,否则要求输入所需的报价,并使用您具有的索引作为参考。

上述方法似乎比前一种更好,但请记住,每个人都喜欢在不同时区的一件事。

答案 1 :(得分:0)

请使用软件包https://github.com/rmawatson/flutter_isolate

对于演示,我每秒显示一次时间信息,您可以根据您的请求进行更改。
如果仅使用隔离器执行此操作,请在按电源按钮后屏幕变黑15分钟以上。您的工作将停止。
使用此软件包可以防止这种情况,您的作业将在15分钟后继续运行。

Timer.periodic(new Duration(seconds: 1), (Timer t) {
      counter++;
      String msg = "${DateTime.now().hour} : ${DateTime.now().minute} ${DateTime.now().second}"; //'notification ' + counter.toString();
      print('SEND: ' + msg);
      sendPort.send(msg);
      //sendPort.send(counter);
    });

完整代码,点击浮动操作按钮开始

import 'package:flutter_isolate/flutter_isolate.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:isolate';
//import 'package:screen/screen.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Isolate Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Isolates'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FlutterIsolate _isolate;
  bool _running = false;
  static int _counter = 0;
  String notification = "";
  ReceivePort _receivePort;

  void _start() async {
    _running = true;
    _receivePort = ReceivePort();
    _isolate = await FlutterIsolate.spawn(_checkTimer, _receivePort.sendPort);
    _receivePort.listen(_handleMessage, onDone:() {
      print("done!");
    });
  }

  static void _checkTimer(SendPort sendPort) async {
    int counter = 0;
    Timer.periodic(new Duration(seconds: 1), (Timer t) {
      counter++;
      String msg = "${DateTime.now().hour} : ${DateTime.now().minute} ${DateTime.now().second}"; //'notification ' + counter.toString();
      print('SEND: ' + msg);
      sendPort.send(msg);
      //sendPort.send(counter);
    });
  }

  void _handleMessage(dynamic data) {
    print('RECEIVED:  ${data}');
    setState(() {
      notification = data.toString();
    });
  }

  void _stop() {
    if (_isolate != null) {
      setState(() {
        _running = false;
        notification = '';
      });
      _receivePort.close();
      //_isolate.kill(priority: Isolate.immediate);
      _isolate.kill();
      _isolate = null;
    }
  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              notification,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _running ? _stop : _start,
        tooltip: _running ? 'Timer stop' : 'Timer start',
        child: _running ? new Icon(Icons.stop) : new Icon(Icons.play_arrow),
      ),
    );
  }
}

enter image description here