/
news_ui.dart
108 lines (97 loc) · 2.98 KB
/
news_ui.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:test_helloworld/TestingListDataBloc/bloc/bloc.dart';
import 'package:test_helloworld/TestingListDataBloc/models/models.dart';
class NewsUi extends StatefulWidget {
@override
_NewsUiState createState() => _NewsUiState();
}
class _NewsUiState extends State<NewsUi> {
final _scrollController = ScrollController();
final _scrollThreshold = 200.0;
PostBloc _postBloc;
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
_postBloc = BlocProvider.of<PostBloc>(context);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (maxScroll - currentScroll <= _scrollThreshold) {
_postBloc.add(Fetch());
}
}
@override
Widget build(BuildContext context) {
return BlocBuilder<PostBloc, PostState>(
builder: (context, state) {
if (state is PostError) {
return Center(
child: Text("Failed to fetch News Data"),
);
}
if (state is PostLoaded) {
if (state.posts.isEmpty) {
return Center(
child: Text("News not Found"),
);
}
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return index >= state.posts.length
? BottomLoader()
: PostWidget(
post: state.posts[index],
);
},
itemCount: state.hasReachedMax
? state.posts.length
: state.posts.length + 1,
controller: _scrollController,
);
}
return Center(
child: CircularProgressIndicator(),
);
},
);
}
}
class BottomLoader extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: Center(
child: SizedBox(
width: 33.0,
height: 33.0,
child: CircularProgressIndicator(
strokeWidth: 1.5,
))));
}
}
class PostWidget extends StatelessWidget {
final Post post;
const PostWidget({Key key, @required this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
leading: Text(
'${post.id}',
style: TextStyle(color: Colors.green[900], fontFamily: 'Avenir',fontSize: 10.0),
),
title: Text(post.title, style: TextStyle(color: Colors.green[900], fontFamily: 'Avenir', fontSize: 18.0, fontWeight: FontWeight.bold),),
isThreeLine: true,
subtitle: Text(post.body, style: TextStyle(color: Colors.green[900], fontFamily: 'Avenir', fontSize: 14.0),),
dense: true,
);
}
}