【问题标题】:How to "Stop Flutter from rebuilding widgets" after app is closed应用程序关闭后如何“停止 Flutter 重建小部件”
【发布时间】:2020-09-07 23:19:20
【问题描述】:

所以我构建了我的第一个应用程序。这是一个天气应用程序。到目前为止,一切都按预期工作。但是有一个问题,每当我关闭应用程序然后重新打开它时,一切都是空的(天气预报、位置名称、最高和最低温度)。当我按下刷新按钮时,它的 null 被更新为当前状态。我想做的是,如果我按下刷新按钮,我希望应用程序显示最后一次刷新并更新它,而不是显示 null。我怎样才能做到这一点。

请记住,我是新手。

ma​​in.dart:

import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'GetLocation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() {
  runApp(AuraWeather());
}

class AuraWeather extends StatefulWidget {
  @override
  _AuraWeatherState createState() => _AuraWeatherState();
}

class _AuraWeatherState extends State<AuraWeather> {

  var apiKey = '5f10958d807d5c7e333ec2e54c4a5b16';
  var description;
  var city;
  var maxTemp;
  var minTemp;
  var temp;

  @override
  Widget build(BuildContext context) {
    setState(() {
      getLocation();
    });

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(displayBackground()),
          ),
        ),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaY: 2, sigmaX: 2),
          child: Container(
            color: Colors.black.withOpacity(0.5),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              body: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      Container(
                        child: Center(
                          child: Text(
                            '$city',
                            style: TextStyle(
                              fontSize: 35,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        child: Icon(
                          FontAwesomeIcons.locationArrow,
                          color: Colors.white,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 80),
                        child: Text(
                          '$temp' + '°',
                          style: TextStyle(
                              fontSize: 50,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Icon(
                      Icons.wb_sunny,
                      color: Colors.white,
                      size: 100,
                    ),
                  ),
                  Container(
                    child: Center(
                      child: Text(
                        '$maxTemp ° | $minTemp °',
                        style: TextStyle(fontSize: 20, color: Colors.white),
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      '$description',
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ),
                  ),
                  Container(
                    child: FlatButton(
                      child: Icon(
                        Icons.refresh,
                        color: Colors.white,
                        size: 40,
                      ),
                      color: Colors.transparent,
                      onPressed: () {
                        setState(
                          () {
                            getLocation();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // display background images based on current time
  displayBackground() {
    var now = DateTime.now();
    final currentTime = DateFormat.jm().format(now);
    if (currentTime.contains('AM')) {
      return 'images/Blood.png';
    } else if (currentTime.contains('PM')) {
      return 'images/Sun.png';
    }
  }

  //getLocation
  void getLocation() async {
    Getlocation getlocation = Getlocation();
    await getlocation.getCurrentLocation();

    print(getlocation.latitude);
    print(getlocation.longitude);
    print(getlocation.city);
    city = getlocation.city;
    getTemp(getlocation.latitude, getlocation.longitude);
  }

  //Get current temp
  Future<void> getTemp(double lat, double lon) async {
    http.Response response = await http.get(
        'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
    //print(response.body);

    var dataDecoded = jsonDecode(response.body);
    description = dataDecoded['weather'][0]['description'];

    temp = dataDecoded['main']['temp'];
    temp = temp.toInt();

    maxTemp = dataDecoded['main']['temp_max'];
    maxTemp = maxTemp.toInt();

    minTemp = dataDecoded['main']['temp_min'];
    minTemp = minTemp.toInt();

    print(temp);
  }
}

GetLocation.dart:

import 'package:geolocator/geolocator.dart';

class Getlocation {

    double latitude;
    double longitude;
    var city;
    //Get current location
    Future<void> getCurrentLocation() async {
        try {
            Position position = await Geolocator()
                    .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
            latitude = position.latitude;
            longitude = position.longitude;

            city = await getCityName(position.latitude, position.longitude);
        } catch (e) {
            print(e);
        }
    }

    //Get city name
    Future<String> getCityName(double lat, double lon) async {
        List<Placemark> placemark =
        await Geolocator().placemarkFromCoordinates(lat, lon);
        print('city name is: ${placemark[0].locality}');
        return placemark[0].locality;
    }
}

【问题讨论】:

    标签: android flutter dart weather


    【解决方案1】:

    简单的解决方案是使用SharedPreferences,然后在刷新天气后将每个变量保存到它,例如

    Future<void> _saveStringInSharedPrefs(String key, String value) async =>
      SharedPreferences.getInstance().then((prefs) => prefs.setString(key, value));
    

    对于每个值。您可能还想将 vars 更改为类型,例如 double、String 等。

    然后您可以将 initState 添加到您的状态,在其中将每个变量设置为 SharedPreferences.getString(variable_key)。使用SharedPreferences prefs = SharedPreferences.getInstance(),然后调用prefs.getString() 会很方便。你可以在构建中添加它,但你可能不应该,构建方法意味着非常快,因此它们可以运行高达 60 次/秒。

    编辑:

        http.Response response = await http.get(
            'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
        //print(response.body);
    
        await SharedPreferences.getInstance().then((prefs) {prefs.setString('weather_data', response.body}) // add this line
    
        var dataDecoded = jsonDecode(response.body);
        // (rest of the code)
    
    

    这会将您的 json 保存到 SharedPrefs。现在您只需要提取适用于 JSON 的函数并设置变量。所以它看起来像这样:

    void _setData(String jsonString) {
        var dataDecoded = jsonDecode(response.body);
        description = dataDecoded['weather'][0]['description'];
    
        // here it would be safer to have temp be of type 'int' instead of 'var' and set it like this:
        // temp = dataDecoded['main']['temp'].toInt();
    
        temp = dataDecoded['main']['temp'];
        temp = temp.toInt();
    
        maxTemp = dataDecoded['main']['temp_max'];
        maxTemp = maxTemp.toInt();
    
        minTemp = dataDecoded['main']['temp_min'];
        minTemp = minTemp.toInt();
    }
    

    然后您可以像这样拆分 getTemp:

      Future<void> getTemp(double lat, double lon) async {
        http.Response response = await http.get(
            'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
        //print(response.body);
    
        _setData(response.body);
      }
    

    然后,当您启动应用程序时,您希望它从 SharedPreferences 加载值。所以将它添加到 _AuraWeatherState:

    @override
    void initState() {
        super.initState();
        _loadData();
    }
    
    Future<void> _loadData() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        _setData(prefs.getString('weather_data'));
    }
    

    这应该可以,但我没有时间检查它是否执行。因此,如果您有任何其他问题,我很乐意为您提供帮助:)

    【讨论】:

    • 您好,谢谢。你能告诉我如何在我的代码上实现它吗?
    • 下班后我会在 5 小时后回复您。
    • 非常感谢!
    • 抱歉耽误了我已经完成了,请尝试是否有效
    • 是这行代码的问题:await SharedPreferences.getInstance().then((prefs) {prefs.setString('weather_data', response.body});
    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多