上一篇我实践了flutter项目的数据传递,这篇我们来看看从后端获取数据~
一:关于请求需要http
pubspec.yaml 文件添加依赖:
dependencies:
flutter:
sdk: flutter
http: ^0.12.0
二:代码:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class Page3 extends StatefulWidget {
Page3({Key key, this.data, this.title}) : super(key: key);
final data;
final title;
@override
_PageState createState() => _PageState();
}
class _PageState extends State<Page3> {
var array = [];
var obj={};
Future<http.Response> fetchPost() async {
final response = await http.get('http://192.168.0.70:5001/');
final data = json.decode(response.body);
setState(() {
//setState 引起页面变化
obj = data;
array = data["items"];
});
return response;
}
@override
void initState() {
//页面初始化
super.initState();
fetchPost();
}
@override
void dispose() {
//页面销毁时
super.dispose();
}
@override
Widget build(BuildContext context) {
print(obj);//将会输出两次
print(array);//将会输出两次
return Scaffold(
body: new Center(
child: Column(
children: <Widget>[
PhysicalModel (
color: Colors.blue,
elevation: 6,
child: Container(
padding: new EdgeInsets.only(top: 50,left: 40, right: 40, bottom: 19),
child: Container(
height: 40.0,
padding: new EdgeInsets.only(left: 10),
decoration: new BoxDecoration(
color: Colors.blue[200],
borderRadius: new BorderRadius.circular(25.0),
),
child: TextFormField(
style: new TextStyle(color: Colors.white70,fontSize: 14),//输入文字颜色和大小
decoration: InputDecoration(
hintText: '请输入订单号搜索',//文字提示
hintStyle: new TextStyle(color: Colors.white70),//提示文字颜色
icon: Icon(Icons.search, color: Colors.white70),//图标
border: InputBorder.none,//去掉下划线
),
),
),
),
),
Container(
padding: new EdgeInsets.only(top: 200),
child: new Image.asset('images/order-empty.png'),
),
new MaterialButton(
onPressed: () {
print(widget.data);
//Navigator.pushNamed(context, '/page2');
},
child: Text('前往配送单,${widget.title}'),
),
],
),
)
);
}
}
输出结果:
下一篇我们看数据渲染~