Skip to content

Instantly share code, notes, and snippets.

@TunvirRahman
Created February 5, 2021 16:25
Show Gist options
  • Select an option

  • Save TunvirRahman/2f96b5ae0b67eb8a4290ceed1acb6308 to your computer and use it in GitHub Desktop.

Select an option

Save TunvirRahman/2f96b5ae0b67eb8a4290ceed1acb6308 to your computer and use it in GitHub Desktop.
http_flutter
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class ToDo {
final int userId;
final int id;
final String title;
final bool completed;
ToDo(this.userId,this.id, this.title,this.completed);
ToDo.fromJson(Map<String, dynamic> json)
: userId = json['userId'],
id = json['id'],
completed = json['completed'],
title = json['title'];
}
class _HomeState extends State<Home>{
List<ToDo> _toDos = [];
bool _loading = false;
void _onCliked() async{
this.setState(() {
_loading= true;
});
var data = await http.get("https://jsonplaceholder.typicode.com/todos");
Iterable arr = json.decode(data.body);
final todos = List<ToDo>.from(arr.map((e) => ToDo.fromJson(e)));
this.setState(() {
_toDos = todos;
_loading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My Application"),
),
body: Center(
child: _loading ? CircularProgressIndicator(backgroundColor: Colors.blue) : ToDoList(todos: _toDos,)
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.sync),
onPressed: _onCliked,
),
);
}
}
class ToDoList extends StatelessWidget{
final List<ToDo> todos;
ToDoList({@required this.todos});
@override
Widget build(BuildContext context) {
return todos.length == 0 ? Text("No data available"):
ListView.separated(
itemBuilder: (context,index){
final item = todos[index];
return ListViewCell(todo: item);
},
separatorBuilder: (context,index){
return SizedBox(
height: 0.1,
child: Container(color: Colors.blue,),
);
},
itemCount: todos.length);
}
}
class ListViewCell extends StatelessWidget{
final ToDo todo;
ListViewCell({@required this.todo});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 40,
child: Text(todo.title,textAlign: TextAlign.center,style: TextStyle(fontWeight: FontWeight.bold,decoration: this.todo.completed? TextDecoration.lineThrough : TextDecoration.none),),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment