如何设置文本值以在颤动中自动更改?

时间:2019-11-05 07:40:47

标签: flutter dart flutter-layout flutter-dependencies

我是扑朔迷离的,并且正在开发一个应用程序,该应用程序在Scaffold中的浮动动作按钮中显示车速。但我希望它根据速度自动更改,这样就不必每次都手动刷新/重新启动。

这是我的代码。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';


class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

double speedInMps;
double speedInKph;
var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, 
distanceFilter: 10);

Future<void> getVehicleSpeed()async{

try{
  geolocator.getPositionStream((locationOptions)).listen((position) async 
{
     speedInMps = await position.speed;
     speedInKph = speedInMps * 1.609344;

     print(speedInKph.round());

  });
}catch(e){
  print(e);
}
}

@override
Widget build(BuildContext context) {

return MaterialApp(
    home: Scaffold(  floatingActionButton: FloatingActionButton(
    onPressed: () {getVehicleSpeed();
},
child: Text(speedInKph.round().toString() +'Km/h'),//Need Improvments 
Here
backgroundColor: Colors.green,
    ),
      appBar: AppBar(
        title: Text('speed'),
        centerTitle: true,
      ),

      body: Center(
        child: FlatButton(
          onPressed: getVehicleSpeed,
          child: Text(
        speedInKph.toString(),
            style: TextStyle(fontSize: 16.0),
          ),
          color: Color(0xffdd4b39),
          textColor: Colors.white,
          padding: const EdgeInsets.all(20.0),
        ),

      ),

    )
 );
}
}

我必须热装/重启才能获得更新的速度,但是我希望它自动刷新速度。

1 个答案:

答案 0 :(得分:0)

您只需收听一次位置。因此,放入initState,在小部件初始化时调用。

@override
void initState() {
  super.initState();
  getVehicleSpeed();
}

然后在数据更改时调用setState方法。它将重建小部件。

Future<void> getVehicleSpeed() async {
    try {
      geolocator.getPositionStream((locationOptions)).listen((position) async {
      speedInMps = position.speed;
      setState(() {
        speedInKph = speedInMps * 1.609344;
      });

      print(speedInKph.round());
    });
  } catch (e) {
    print(e);
  }
}