Skip to content

Instantly share code, notes, and snippets.

@felagund18
Last active July 23, 2018 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felagund18/08ed2a8886fde95779563e6acf3157e2 to your computer and use it in GitHub Desktop.
Save felagund18/08ed2a8886fde95779563e6acf3157e2 to your computer and use it in GitHub Desktop.
FutureBuilder test
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