android - 应用关闭后如何 “Stop Flutter from rebuilding widgets”

标签 android flutter dart weather

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

请记住,我是新手。

main.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;
    }
}

最佳答案

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

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

每个值。您可能还想将var更改为类型,例如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'));
}

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

关于android - 应用关闭后如何 “Stop Flutter from rebuilding widgets”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61932618/

相关文章:

dart - Stack 中个别 child 的适合度

regex - Dart : How to extract youtube video ID from video URL?

dart - 包含项目 : within Flutter DropdownButton, 的 map 中的返回语句 为什么以及如何工作

dart - HashMap 没有实例键

java - com.google.android.gms.location.LocationListener 无法转换为 android.location.LocationListener

flutter - 如何在Google上创建类似于 'my activity'的用户历史记录页面-Flutter

java - Android Fragment 中的 Volley 请求队列(getApplicationContext 可能会产生 NullPointerException)

flutter - Dart:WAITING函数调用不等待并返回 Future 对象

android - 致命 : Cannot get https://gerrit. googlesource.com/git-repo/clone.bundle 致命:错误 [Errno 110] 连接超时

android - 如何从 fragment 开始服务