Last active
July 23, 2018 18:28
-
-
Save felagund18/08ed2a8886fde95779563e6acf3157e2 to your computer and use it in GitHub Desktop.
FutureBuilder test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
import 'dart:async'; | |
import 'dart:convert'; | |
class tab1 extends StatelessWidget { | |
Future<List> _getData() async { | |
final response = await http.get('https://api.androidhive.info/contacts/'); | |
if (response.statusCode == 200) { | |
return json.decode(response.body)['contacts']; | |
} | |
return []; | |
} | |
Widget _buildListView(BuildContext context, List data) { | |
return new ListView.builder( | |
itemCount: data.length, | |
itemBuilder: (BuildContext context, int index) { | |
return new Column( | |
children: <Widget>[ | |
new ListTile( | |
title: new Text(data[index]['name']), | |
), | |
new Divider(height: 2.0,), | |
], | |
); | |
}, | |
); | |
} | |
@override | |
Widget build(BuildContext context) { | |
//getData(); // fetching data from an API in build function causes performance issues, everytime setState() is called, getData() will be called... | |
return new Container( | |
child: new FutureBuilder( | |
future: _getData(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
if (snapshot.hasData) { | |
if (snapshot.data != null) { | |
return _buildListView(context, snapshot.data); | |
} | |
} | |
return new CircularProgressIndicator(); | |
} | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment