首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Dart中每24小时更改一次文本

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

Stack Overflow用户
提问于 2019-09-02 03:30:25
回答 2查看 2.3K关注 0票数 0

所以基本上我正在创建一个应用程序,在应用程序的主页上有一个“当天的引用”。我已经把报价装在集装箱里了,但我不能让报价每24小时换一次。

我对Dart还不熟悉,但利用过去在其他编程语言上的知识,我想我需要使用一个if- other语句,它也使用设备的内部时钟。我在想,它将是"If(0:00 AM){在数组}nothing{do nothing}中显示下一个引号“。

代码语言:javascript
运行
复制
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}";
    });
  } 
}

无论我尝试了多少次,这种方法都不起作用,但这可能是由于我的知识有限。任何一点信息都有帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-02 07:23:00

使用2个变量。

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

如果两个时间戳的两天是不同的,那么请求一个随机报价。

如果您担心用户可能会占用他的手机时间,请使用SharePreferences在本地存储前面的引号。

如果您希望每天显示特定的引号,然后为每个引号存储密钥对或索引对或日期-引号对值,并对索引/键/日期进行第一次请求,如果它等于存储在用户电话中的旧索引/键/日期值,则不要请求新的引用请求,并使用您的索引作为参考。

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

票数 2
EN

Stack Overflow用户

发布于 2019-09-02 06:27:43

请使用isolate软件包

对于演示,我每一秒显示一次时间信息,您可以根据您的请求进行更改。

如果您只使用隔离,在您按下电源按钮和屏幕变成黑色超过15分钟。你的工作就会停止。

使用此包可以防止这种情况,您的作业将在15分钟后继续运行。

代码语言:javascript
运行
复制
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);
    });

完整代码,单击浮动操作按钮启动。

代码语言:javascript
运行
复制
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),
      ),
    );
  }
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57751110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档