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'],
    );
  }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值