【问题标题】:Flutter set floatingactionbutton text on interval basisFlutter基于间隔设置floatingactionbutton文本
【发布时间】:2019-01-29 16:52:18
【问题描述】:

我有以下小部件,它将适合不同的父小部件进入其正文部分。所以在父小部件中,我将这个小部件称为如下 body: MapsDemo(),。现在的问题是,在本节中,我每隔 30 秒运行一次间隔,我想调用 api 以获取所有最新标记。 目前我打印倒计时,因为这个代码print("${30 - timer.tick * 1}"); 我的问题很简单,我有 3 个三个浮动操作按钮,我给了他们他们的 ID。因此,在最后一个浮动操作按钮 btn3.text 的每个倒计时中,我试图将其值设置为 ${30 - timer.tick * 1} 但它在此基础上不起作用。如何更新按钮中的倒计时?

class MapsDemo extends StatefulWidget {
  @override
  State createState() => MapsDemoState();
}

class MapsDemoState extends State<MapsDemo> {
  GoogleMapController mapController;
  @override
    void initState() {
      super.initState();      
      startTimer(30);
    }

    startTimer(int index) async {

      print("Index30");
      print(index);
      new Timer.periodic(new Duration(seconds: 1), (timer) {
        if ((30 / 1) >= timer.tick) {
          print("${30 - timer.tick * 1}");
          btn3.text = ${30 - timer.tick * 1};
        } else {
          timer.cancel();
          var responseJson = NetworkUtils.getAllMarkers(
                   authToken
               );
          mapController.clearMarkers();
          //startTimer(index + 1);
        }
      });

  }

 //Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.contacts]);import 'package:permission_handler/permission_handler.dart';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: Stack(
            children: <Widget>[

              GoogleMap(
                  onMapCreated: (GoogleMapController controller) {
                   mapController = controller;

                 },
                initialCameraPosition: new CameraPosition(target: LatLng(3.326411697920109, 102.13127606037108))
                ),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Align(
                    alignment: Alignment.topRight,
                    child: Column(
                    children: <Widget>[  
                     FloatingActionButton(
                      onPressed: () => print('button pressed'),
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.lightBlue,
                      child: const Icon(Icons.map, size: 30.0),
                      heroTag: "btn1",

                     ),
                    SizedBox(height: 5.0),
                    FloatingActionButton(
                        onPressed: () => print('second  pressed'),
                        materialTapTargetSize: MaterialTapTargetSize.padded,
                        backgroundColor: Colors.lightBlue,
                        child: const Icon(Icons.add, size: 28.0),
                        heroTag: "btn2",
                      ),
                      SizedBox(height: 5.0),
                      FloatingActionButton(
                        onPressed: () => print('second  pressed'),
                        materialTapTargetSize: MaterialTapTargetSize.padded,
                        backgroundColor: Colors.lightBlue,
                        child: const Icon(Icons.directions_bike, size: 28.0),
                        heroTag: "btn3",

                      ),
                    ]
                  )
                  ),
                ),
            ]

         )
    );
  }
}

【问题讨论】:

    标签: dart flutter floating-action-button


    【解决方案1】:

    下面将在FloatingActionButton 内显示从 30 秒开始的倒计时。

    import 'dart:async';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'FAB Countdown Demo',
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      static const _defaultSeconds = 30;
      Timer _timer;
      var _countdownSeconds = 0;
    
      @override
      void initState() {
        _timer = Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
        super.initState();
      }
    
      @override
      void dispose() {
        _timer.cancel();
        super.dispose();
      }
    
      void _getTime() {
        setState(() {
          if (_countdownSeconds == 0) {
            _countdownSeconds = _defaultSeconds;
          } else {
            _countdownSeconds--;
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: AppBar(
            title: const Text('FAB Countdown Demo'),
          ),
          floatingActionButton: FloatingActionButton(
              child: Text('$_countdownSeconds'), onPressed: () {}),
        );
      }
    }
    

    【讨论】:

    • 我需要调用这个函数 var responseJson = NetworkUtils.getAllMarkers( authToken );每 30 秒结束后开始下一个间隔。在我开始下一个间隔之前,我应该怎么做才能等待结果返回?
    • @newbie 网络调用是Futures,因此您可以在then 回调被触发时等待重新启动间隔,或者在重新启动间隔之前使用await 表达式返回。
    • 无论如何我对这个未来的概念有点新静态动态成为其中的一部分吗?所以在这种情况下,函数是异步的,在哪里定义 then ?
    • @newbie 你应该阅读fetching data from flutterDart futures。您不需要拨打电话static,但我会定义类型而不是留下它dynamicthen 是一个回调,如果 getAllMarkers 是返回适当值的正确 Future,则可以使用该回调。 await 之后的代码只有在您的 Future 完成一个值后才会继续。 await 只是让你的代码看起来像同步代码。
    • 我使用了静态,因为我只是在关注一些示例,而动态是因为它会发送单个字符串,如失败或 json。实际上是一个rest api调用。所以根据你的建议,我的函数定义有什么问题,我应该如何返回我的 rest api 值?
    猜你喜欢
    • 2021-04-09
    • 2018-09-02
    • 2015-01-23
    • 2016-08-05
    • 2018-01-19
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多