Skip to content

Instantly share code, notes, and snippets.

@Tajcore
Last active July 23, 2020 02:27
Show Gist options
  • Save Tajcore/cdaf439ec8b38b875ac8e1ab159514a8 to your computer and use it in GitHub Desktop.
Save Tajcore/cdaf439ec8b38b875ac8e1ab159514a8 to your computer and use it in GitHub Desktop.
Sample request to an API with Flutter using ASYNC function
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class SongList extends StatefulWidget {
SongList({Key key}) : super(key: key);
@override
_SongListState createState() => _SongListState();
}
class _SongListState extends State<SongList> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("API Test"),
),
body: Container(
child: FutureBuilder(
future: getSongs(),
builder: (context, snapshot) {
return snapshot.connectionState == ConnectionState.waiting
? Container(
child: Center(
child: CircularProgressIndicator(),
))
: Column(children: <Widget>[
Expanded(
child: ListView.builder(
shrinkWrap: false,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index].title),
trailing: Icon(Icons.music_note));
})),
]);
},
),
),
);
}
getSongs() async {
List<SongAlbum> albums = new List<SongAlbum>();
var respondBody =
await http.get('https://jsonplaceholder.typicode.com/albums/');
for (var data in json.decode(respondBody.body)) {
SongAlbum album = SongAlbum.fromJson(data);
albums.add(album);
}
return albums;
}
}
class SongAlbum {
int id;
String title;
SongAlbum({
this.id,
this.title,
});
SongAlbum copyWith({
int id,
String title,
}) {
return SongAlbum(
id: id ?? this.id,
title: title ?? this.title,
);
}
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
};
}
static SongAlbum fromMap(Map<String, dynamic> map) {
if (map == null) return null;
return SongAlbum(
id: map['id'],
title: map['title'],
);
}
String toJson() => json.encode(toMap());
factory SongAlbum.fromJson(Map<String, dynamic> json) {
return SongAlbum(
id: json['id'],
title: json['title'],
);
}
@override
String toString() => 'SongAlbum(id: $id, title: $title)';
@override
bool operator ==(Object o) {
if (identical(this, o)) return true;
return o is SongAlbum && o.id == id && o.title == title;
}
@override
int get hashCode => id.hashCode ^ title.hashCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment