簡體   English   中英

如何在 flutter 中設置文本值自動更改?

[英]How to set text values to change automatically in flutter?

我是 flutter 的新手,我正在開發一個應用程序,其中車速顯示在腳手架的浮動操作按鈕中。 但我希望它根據速度自動改變,這樣它就不需要每次都手動刷新/重啟。

這是我的代碼。

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),
        ),

      ),

    )
 );
}
}

我必須熱重載/重新啟動才能獲得更新的速度,但我希望它自動刷新速度。

您只需要聽一次位置。 因此,放入在小部件初始化時調用的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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM