【问题标题】:How to hit an API when time is 00:00 in Flutter?Flutter 中时间为 00:00 时如何访问 API?
【发布时间】:2019-11-19 17:24:51
【问题描述】:

我正在开发我的第一个 Flutter 应用程序。有一个活动/屏幕显示倒计时时间。我想,当时间是 00:00 时,然后点击 API。

我尝试并搜索它,但我没有找到关于这个问题的最佳信息。 请告诉我如何解决这个问题? 谢谢。


String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  String time;
  String topicName;
  Future<String> getTime() async{
    final response = await http.post(Constant.TestTime,
        body: {
          "topic_id" : widget.valueTopicId,
        });

    Map<String,dynamic> respons = jsonDecode(response.body);

    setState(() {
      time=respons['test_time'];
      topicName=respons['topic_name'];
      controller = AnimationController(
        vsync: this,
        duration: Duration(minutes:int.parse(time) ,seconds: 00),
      );

      if (controller.isAnimating)
        controller.stop();
      else {
        controller.reverse(
            from: controller.value == 0.0
                ? 1.0
                : controller.value);
      }
    });
    print(respons.toString());
    setState(() {
      isLoading=false;
    });
  }


Widget _buildAppBar (BuildContext context){
    return PreferredSize (preferredSize: Size.fromHeight(MediaQuery.of(context).size.height * 0.085),
    child: AppBar(
      backgroundColor: Colors.blue,
      title: Text("Questions"),
      centerTitle: true,
      iconTheme: IconThemeData(
          color: Colors.white
      ),
      actions: <Widget>[
        new Container(
          margin: const EdgeInsets.only(top: 25.0, left: 25.0),
          child: new Text(topicName,
            style: TextStyle(color: Colors.white, fontSize: 26,
                fontWeight: FontWeight.bold),),
        ),
        SizedBox(width: 20),
        new Padding(padding: EdgeInsets.all(20.0)),
        new Padding(padding: EdgeInsets.only(bottom: 40, top: 50)),
        Expanded(
            flex: 1,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Expanded(
                  child: Align(
                      alignment: FractionalOffset.center,
                      child: AspectRatio(aspectRatio: 1.0,
                        child: Stack(
                          children: <Widget>[
                            Positioned.fill(child:
                            AnimatedBuilder(
                              animation: controller,
                              builder: (BuildContext context,
                                  Widget child) {
                                return Padding(
                                  padding: const EdgeInsets.all(5.0),
                                  child: CustomPaint(
                                    painter: TimerPainter(
                                      animation: controller,
                                      backgroundColor: Colors.white,
                                      color: Colors.blue,
                                    ),
                                  ),
                                );
                              },
                            ),
                            ),
                            Align(
                              alignment: FractionalOffset.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment
                                    .spaceEvenly,
                                crossAxisAlignment: CrossAxisAlignment
                                    .center,
                                children: <Widget>[
                                  AnimatedBuilder(
                                      animation: controller,
                                      builder: (BuildContext context,
                                          Widget child) {
                                        return Text(
                                          timerString, style: TextStyle(
                                            color: Colors.white),
                                        );
                                      }
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      )
                  ),
                ),
              ],
            )
        )
      ],
    ) ,);

  }


  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onBackPressed,
      child: isLoading
          ? Center(child: CircularProgressIndicator(),)
          :MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            resizeToAvoidBottomPadding: false,
            appBar: _buildAppBar(context),
            body: Questions(widget.valueTopicId,widget.noOfQuestions,widget.difficulty,time),
          )
      ),
    );
  }
}

在这里我发布了我的代码,API getTime() 正在访问 initState()。所以,当我的时间是 00:00 时,应该点击另一个 API。我尝试使用 FutureBuilder 但它没有用。可能是我做错了什么,但在这方面很混乱。

【问题讨论】:

    标签: flutter flutter-layout flutter-dependencies


    【解决方案1】:

    可以使用Timer,需要导入dart:async

    Timer(Duration(seconds: 5), () {
      getTime();
    });
    

    【讨论】:

    • 我应该在哪里做这个?
    • @AbhitGahlot 你可以把它放在 initState 方法中。
    • 但是initState会在屏幕出现时调用,那么你认为它将如何运行?
    • 如果我在 5 秒后调用这个 API 会发生什么?
    【解决方案2】:

    您需要在initState 中注册您的计时器。 Timer.periodic() 将在指定时间后的特定持续时间内执行。

    Timer _timer;
    
    @override
    void initState()
    {
         _timer = Timer.periodic(
                   const Duration(seconds: 1), (Timer t) => handleAPICall(),
                );   
         super.initState();
    }
    
    @override
    void dispose()
    {
        _timer?.cancel();
        super.dispose();
    }
    
    void handleAPICall()
    {
      // here you need to check if its time to make the API call.
      // I am assuming that you will have some datetime that will tell you 
      // if duration time is 00:00
    
      if(duration_time == 00:00) // you need to write your correct logic
      {
         // then, make the HTTP Call.
      }      
    }   
    

    【讨论】:

    • 我认为你没有得到我的问题,你能在这里看到我的代码吗dpaste.de/uFwL
    • 当您的Duration00:00 时我的理解是什么,那么您需要使用另一个API。那么,请帮助我了解您的问题是点击第二个 API 还是第一个 API ??
    • 先生,我想进入另一个屏幕...这个计时器在我的 appBar 中,我试过这样: String get timerString { Duration duration = controller.duration * controller.value; if("${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}"=="00:00"){ print("true"); setState(() { var rou = new MaterialPageRoute( builder: (BuildContext con) =>new Screen()); Navigator.of(context).push(rou); }); } return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}'; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多