Flutter实战4 -- 天气查询APP重构之状态管理(InheritedWidget)

栏目: IOS · Android · 发布时间: 7年前

内容简介:前面三篇文章:写了一个很简单的应用,在将这个APP的功能复杂化之前,我们必须要选择一个合适的框架,这样才能避免代码失控,就是随着APP功能的增加,代码的结构和管理越来越复杂。本篇文章将如何使用InheritedWidget来管理状态。本篇文章所涉及的代码:

前面三篇文章:

  1. Flutter实战1 --- 写一个天气查询的APP
  2. Flutter实战2 --- 写一个天气查询的APP
  3. FFlutter实战3 --- PC上运行Flutter APP

写了一个很简单的应用,在将这个APP的功能复杂化之前,我们必须要选择一个合适的框架,这样才能避免代码失控,就是随着APP功能的增加,代码的结构和管理越来越复杂。本篇文章将如何使用InheritedWidget来管理状态。

0x01 代码

本篇文章所涉及的代码:

github.com/google/flut…

分支:InheritedWidget

0x02 InheritedWidget简介

InheritedWidget用于在树中传递信息

  • 为何InheritedWidget可以用于传递信息?

因为InheritedWidget的实现类似全局单例,可以在树中的任何位置都拿到InheritedWidget的单例对象,所以可以做到在树中传递信息。

0x03 InheritedWidget功能

InheritedWidget继承自ProxyWidget,ProxyWidget继承自Widget,可以单独使用,但是没有状态,为了有状态,一般和StatefulWidget搭配使用,搭配方法的示例如下: 需要有三个类:

  1. AppStateWidget(继承StatefulWidget)
  2. AppState (创建InheritedWidget,AppState持有数据及业务逻辑)
  3. InheritedWidget(持有AppState)

0x04 天气查询APP重构

接下来我们要写一个状态管理的类,这个类持有天气查询APP里所有的数据,以及实现数据请求的功能。代码如下:

import 'dart:convert';

import 'package:flutter/widgets.dart';
import 'package:gdg_weather/page/city/CityData.dart';
import 'package:gdg_weather/page/weather/WeatherData.dart';
import 'package:http/http.dart' as http;

//StatefulWidget 和 InheritedWidget配合使用
class WeatherControllerWidget extends StatefulWidget{
  Widget child;

  //这里需要传入child,这个参数,InheritedWidget初始化的时候需要用到
  WeatherControllerWidget({this.child});
  
  //这里和其他StatefulWidget一样,返回一个state
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return WeatherControllerState();
  }

  //这里提供了一个static方法,是为了外面好获取
  static WeatherControllerState of(BuildContext context){
    return (context.inheritFromWidgetOfExactType(_WeatherInheritedWidget) as _WeatherInheritedWidget).state;
  }

}

//这个类是核心,用于状态管理,持有数据,并且功能都在这里实现
class WeatherControllerState extends State<WeatherControllerWidget>{

  //持有的数据
  List<CityData> cityList = new List<CityData>();
  String curCityName;
  WeatherData weather = WeatherData.empty();

  //获取城市列表的方法
  void getCityList() async {
    final response = await http.get('https://search.heweather.net/top?group=cn&key=ebb698e9bb6844199e6fd23cbb9a77c5');

        List<CityData> list = new List<CityData>();

        if(response.statusCode == 200){
          //解析数据
          Map<String,dynamic> result = json.decode(response.body);
          for(dynamic data in result['HeWeather6'][0]['basic']){
            CityData cityData = CityData(data['location']);
            list.add(cityData);
          }
        }

        setState(() {
                  cityList = list;
                });
  }

  //获取当前城市的实时天气
  void getCityWeather() async{
    final response = await http.get('https://free-api.heweather.com/s6/weather/now?location='+curCityName+'&key=ebb698e9bb6844199e6fd23cbb9a77c5');
    if(response.statusCode == 200){
      setState(() {
              weather = WeatherData.fromJson(json.decode(response.body));
            });
    }else{
      setState(() {
              weather = WeatherData.empty();
            });
    }
  }
  
  //表示选择了哪个城市
  void selectCity(String city){
    curCityName = city;
  }

  //这里返回了_WeatherInheritedWidget
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return _WeatherInheritedWidget(
      state: this,
      child: widget.child,
    );
  }

}

//_WeatherInheritedWidget
class _WeatherInheritedWidget extends InheritedWidget{
  WeatherControllerState state;

  _WeatherInheritedWidget({
    Key key,
    @required this.state,
    @required Widget child
  }):super(key: key,child: child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    // TODO: implement updateShouldNotify
    return true;
  }

}
复制代码

0x05 传递数据

获取WeatherState的方法:

final weatherState = WeatherControllerWidget.of(context);
复制代码

具体例子如下:

class CityState extends State<CityWidget>{

  CityState(){
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    final weatherState = WeatherControllerWidget.of(context);
    weatherState.getCityList();
    return ListView.builder(
        itemCount: weatherState.cityList.length,
        itemBuilder: (context,index){
          return ListTile(
            title: GestureDetector(
              child:  Text(weatherState.cityList[index].cityName),
              onTap:(){
                weatherState.selectCity(weatherState.cityList[index].cityName);
                Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => WeatherWidget())
                );
              },
            ),
          );
        });
  }

}
复制代码

0x06 InheritedWidget的作用域

InheritedWidget的作用域只能包括自己及自己的子节点,所以InheritedWidget在树中只能向下传递,所以在天气查询的APP中,为了让InheritedWidget的作用域是全局的,得这么做:

void main(){
  runApp(WeatherControllerWidget(child: MyApp()));
}
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML5

HTML5

Matthew David / Focal Press / 2010-07-29 / USD 39.95

Implement the powerful new multimedia and interactive capabilities offered by HTML5, including style control tools, illustration tools, video, audio, and rich media solutions. Understand how HTML5 is ......一起来看看 《HTML5》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

MD5 加密
MD5 加密

MD5 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具