Flutter之网络编程与数据存储

 获取网络上的所需信息是开发APP必不可少的一个部分

我们可以利用http这个组件来进行操作

Future:表示未来某个时间可能会发生的错误或可用结果

http.response是一个成功的HTTP请求接受到的数据

我们通过fetchPost.then()来获得Flutter的返回结果

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Http extends StatefulWidget {
  @override
  _HttpState createState() => _HttpState();
}

class _HttpState extends State<Http> {
  String showResult = '';

  Future<CommonModel> fetchPost() async {//异步操作,把http.response转化为一个CommonModel对象,需要用到dart:convert包
    final response = await http
        .get('http://www.devio.org/io/flutter_app/json/test_common_model.json');//获得一个可用结果
    Utf8Decoder utf8decoder = Utf8Decoder();//我们要用utf-8来进行编码,以避免出现中文乱码的情况
    final result = json.decode(utf8decoder.convert(response.bodyBytes));//如果要利用json进行utf-8标准编码需要这样写
    return CommonModel.fromJson(result);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('http'),
          leading: Icon(Icons.arrow_back),
        ),
        body: Column(
          children: <Widget>[
            InkWell(
              onTap: () {
                fetchPost().then((CommonModel value) {
                  setState(() {
                    showResult =
                        '请求结果:\ntitle:${value.title}\n icon:${value.icon}\n url:${value.url}\n barcolor:${value.barcolor}\n hideAppBar:${value.hideAppBar}\n';//换行为了更条理
                  });
                });
              },
              child: Container(
                width: 180,
                height: 200,
                color: Colors.lightBlue,
                child: Text(
                  '点我',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 50),
                ),
              ),
            ),
            Text(showResult,style: TextStyle(
              fontSize: 22.0,
            ),),
          ],
        ),
      ),
    );
  }
}

class CommonModel {
  final String icon;
  final String title;
  final String barcolor;
  final String url;
  final bool hideAppBar;

  CommonModel(
      {this.icon, this.title, this.barcolor, this.url, this.hideAppBar});

  factory CommonModel.fromJson(Map<String, dynamic> json) {//这个工厂构造函数允许我们通过json来创建一个CommonModel对象
    return CommonModel(
      icon: json['icon'],
      title: json['title'],
      barcolor: json['barcolor'],
      url: json['url'],
      hideAppBar: json['hideAppBar'],
    );
  }
}
发布了99 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43721423/article/details/100144696