flutter 因为setState()不更改值

42fyovps  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(226)

我正在编写代码,setstate工作正常,直到尝试进行其他更改后,setState不再更改变量的值。这是什么原因?

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:weather/weather.dart';
import 'package:weatherapk/widgets/customs_color.dart';
import '../controller/global_controller.dart';
import 'package:intl/intl.dart';

class TemperatureWidget extends StatefulWidget {
  const TemperatureWidget({super.key});

  @override
  State<TemperatureWidget> createState() => _TemperatureWidgetState();
}

class _TemperatureWidgetState extends State<TemperatureWidget> {
  RxString iconText = "".obs;
  RxDouble temperature = 0.0.obs;
  final GlobalController globalController =
      Get.put(GlobalController(), permanent: true);

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

  getAddress() async {
    WeatherFactory wf = WeatherFactory("fbe4f636d052c6acacb97519f02e3b99",
        language: Language.SPANISH);
    Weather w = await wf.currentWeatherByLocation(
        globalController.getLatitude().value,
        globalController.getlongitude().value);
    setState(() {
      iconText.value = "10d";
      iconText.refresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
      Image.network(
        "https://openweathermap.org/img/wn/${iconText.value}@2x.png",
        height: 80,
        width: 80,
      ),
      Container(
        height: 50,
        width: 1,
        color: CustomColors.dividerline,
      ),
    ]);
  }
}

我搜索了类似的论坛,并尝试WidgetisBinding,它仍然没有给出替代。

bfnvny8b

bfnvny8b1#

getAddress是一个Future方法,它需要一些帧来获取数据。对于这种情况,使用FutureBuider更好,也是推荐的。现在我只是在收到日期后调用setState,而不使用getx。

class _TemperatureWidgetState extends State<TemperatureWidget> {
  String iconText = "";
  double temperature = 0.0;

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

  getAddress() async {
    WeatherFactory wf = WeatherFactory("fbe4f636d052c6acacb97519f02e3b99",
        language: Language.SPANISH);
    Weather w = await wf.currentWeatherByLocation(
        globalController.getLatitude().value,
        globalController.getlongitude().value);
    setState(() {
      iconText = "10d";
    });
  }

仅使用iconText,初始帧可能显示图像错误,取决于api。

相关问题