|
| 1 | +import 'package:flutter/material.dart'; |
| 2 | +import 'package:http/http.dart' as http; //for making request |
| 3 | +import 'dart:async'; //for asynchronous features |
| 4 | +import 'dart:convert'; |
| 5 | + |
| 6 | +void main() { |
| 7 | + runApp(new MyApp()); |
| 8 | +} |
| 9 | + |
| 10 | +class MyApp extends StatefulWidget { |
| 11 | + @override |
| 12 | + State<StatefulWidget> createState() { |
| 13 | + return new MyAppScreenMode(); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class MyAppScreenMode extends State<MyApp> { |
| 18 | + @override |
| 19 | + Widget build(BuildContext context) { |
| 20 | + return new MaterialApp( |
| 21 | + title: 'Future Builder', |
| 22 | + theme: new ThemeData( |
| 23 | + primarySwatch: Colors.blue, |
| 24 | + ), |
| 25 | + home: new Scaffold( |
| 26 | + appBar: new AppBar( |
| 27 | + title: new Text('Future Builder'), |
| 28 | + ), |
| 29 | + body: new Center( |
| 30 | + child: new MiddleSection(), |
| 31 | + ))); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class MiddleSection extends StatefulWidget { |
| 36 | + @override |
| 37 | + State<StatefulWidget> createState() { |
| 38 | + return new MiddleSectionState(); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +class MiddleSectionState extends State<MiddleSection> { |
| 43 | + String display; |
| 44 | + |
| 45 | + Widget futureWidget() { |
| 46 | + return new FutureBuilder<String>( |
| 47 | + future: getDataFB(), |
| 48 | + builder: (context, snapshot) { |
| 49 | + if (snapshot.hasData) { |
| 50 | + return new Text( |
| 51 | + snapshot.data.toString(), |
| 52 | + textAlign: TextAlign.center, |
| 53 | + overflow: TextOverflow.ellipsis, |
| 54 | + style: new TextStyle(fontWeight: FontWeight.bold), |
| 55 | + ); |
| 56 | + } else if (snapshot.hasError) { |
| 57 | + return new Text("${snapshot.error}"); |
| 58 | + } |
| 59 | + |
| 60 | + return new CircularProgressIndicator(); |
| 61 | + }, |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + @override |
| 66 | + Widget build(BuildContext context) { |
| 67 | + return new Container( |
| 68 | + color: Colors.yellowAccent, |
| 69 | + width: 250.0, |
| 70 | + padding: const EdgeInsets.all(10.0), |
| 71 | + child: new Column( |
| 72 | + mainAxisAlignment: MainAxisAlignment.spaceEvenly, |
| 73 | + children: <Widget>[ |
| 74 | + new Text("Future Builder Demo"), |
| 75 | + futureWidget() |
| 76 | + ])); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +Future<String> getDataFB() async { |
| 81 | + http.Response response = await http.get( |
| 82 | + Uri.encodeFull("https://jsonplaceholder.typicode.com/posts"), |
| 83 | + headers: {"Accept": "application/json"}); |
| 84 | + List data = JSON.decode(response.body); |
| 85 | + print(data[1]['title'].toString()); |
| 86 | + return data[1]['title'].toString(); |
| 87 | +} |
0 commit comments