如何设置文本值使其在颤动中自动改变?

问题描述 投票:0回答:1

我不熟悉并开发一个应用程序,该应用程序在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),
        ),

      ),

    )
 );
}
}

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

flutter dart flutter-layout flutter-dependencies
1个回答
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);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.