Skip to content

Instantly share code, notes, and snippets.

@Knyazik01
Created Jul 4, 2020
Embed
What would you like to do?
flutter
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void sortList(list) {
return list.sort((a, b) => a.toString().compareTo(b.toString()));
}
Future<Album> fetchAlbum(index) async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/$index');
// await http.get('https://jsonplaceholder.typicode.com/todos/$index');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album({this.userId, this.id, this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum(5);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'V_kn`s test app',
theme: ThemeData(
primaryColor: Colors.black,
),
home: Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text('V_Kn`s app'),
// Icon(
// Icons.favorite,
// color: Colors.indigoAccent,
// size: 24.0,
// semanticLabel: 'Sort',
// ),
Row(children: [
IconButton(
icon: Icon(Icons.sort_by_alpha, color: Colors.indigoAccent),
tooltip: 'Sort by name',
onPressed: (){
sortList(List);
},
),
Text('Sort by name')
])
]),
),
body: Center(
child: new ListView(
children: new List.generate(10, (index) =>
new ListTile(
title:
// Text('Item $index')
FutureBuilder<Album>(
future: fetchAlbum(index+1),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(
child: CircularProgressIndicator()
);
},
),
)
),
)
// FutureBuilder<Album>(
// future: futureAlbum,
// builder: (context, snapshot) {
// if (snapshot.hasData) {
// return Text(snapshot.data.title);
// } else if (snapshot.hasError) {
// return Text("${snapshot.error}");
// }
//
// // By default, show a loading spinner.
// return CircularProgressIndicator();
// },
// ),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment