future builder

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

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String url='http://jsonplaceholder.typicode.com/posts';
getData(){return http.get(url);}
@override
Widget build(BuildContext context) {
getData();
return Scaffold(
appBar: AppBar(title: Text('Http Demo'),),
body: FutureBuilder(
future: getData(),
builder: (BuildContext context, snapshot){
if(!snapshot.hasData){
return Container(
width: window.physicalSize.width,
height: window.physicalSize.height,
color: Colors.lime,
child: Padding(
padding: const EdgeInsets.all(50),
child: CircularProgressIndicator(),
),
);
}
List datas=[];
datas=jsonDecode(snapshot.data.body);
return ListView.builder(
itemCount: datas.length,
itemBuilder: (BuildContext context,index){
var data=datas[index];
return ListTile(
title: Text(data['title']),
subtitle: Text(data['body']),
);
},
);
},
),
);
}
}
posted @ 2019-04-29 00:21  braveheart007  阅读(267)  评论(0编辑  收藏  举报