Как настроить текстовые значения для автоматического изменения в флаттере? - PullRequest
0 голосов
/ 05 ноября 2019

Я новичок в разработке и разработке приложения, в котором скорость транспортного средства отображается на кнопке плавающего действия в 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 голосов
/ 05 ноября 2019

Вам нужно прослушать локацию только один раз. Поэтому вставьте 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);
  }
}
...