TweetsListPage.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_osc/model/constants.dart';
  3. import 'package:flutter_osc/events/LoginEvent.dart';
  4. import 'package:flutter_osc/util/Utf8Utils.dart';
  5. import '../util/BlackListUtils.dart';
  6. import '../model/api.dart';
  7. import '../util/NetUtils.dart';
  8. import '../pages/TweetDetailPage.dart';
  9. import 'login_page.dart';
  10. import 'dart:convert';
  11. import 'dart:async';
  12. import '../util/DataUtils.dart';
  13. class TweetsListPage extends StatefulWidget {
  14. @override
  15. State<StatefulWidget> createState() {
  16. return TweetsListPageState();
  17. }
  18. }
  19. class TweetsListPageState extends State<TweetsListPage> {
  20. List? hotTweetsList;
  21. List? normalTweetsList;
  22. TextStyle? authorTextStyle;
  23. TextStyle? subtitleStyle;
  24. RegExp regExp1 = RegExp("</.*>");
  25. RegExp regExp2 = RegExp("<.*>");
  26. num curPage = 1;
  27. bool loading = false;
  28. ScrollController? _controller;
  29. bool isUserLogin = false;
  30. @override
  31. void initState() {
  32. super.initState();
  33. DataUtils.isLogin().then((isLogin) {
  34. setState(() {
  35. this.isUserLogin = isLogin;
  36. });
  37. });
  38. Constants.eventBus.on().listen((event) {
  39. setState(() {
  40. this.isUserLogin = true;
  41. });
  42. });
  43. Constants.eventBus.on().listen((event) {
  44. setState(() {
  45. this.isUserLogin = false;
  46. });
  47. });
  48. }
  49. TweetsListPageState() {
  50. authorTextStyle =
  51. TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold);
  52. subtitleStyle =
  53. TextStyle(fontSize: 12.0, color: const Color(0xFFB5BDC0));
  54. _controller = ScrollController();
  55. _controller!.addListener(() {
  56. var maxScroll = _controller!.position.maxScrollExtent;
  57. var pixels = _controller!.position.pixels;
  58. if (maxScroll == pixels) {
  59. // load next page
  60. curPage++;
  61. getTweetsList(true, false);
  62. }
  63. });
  64. }
  65. getTweetsList(bool isLoadMore, bool isHot) {
  66. DataUtils.isLogin().then((isLogin) {
  67. if (isLogin) {
  68. DataUtils.getAccessToken().then((token) {
  69. if (token == null || token.length == 0) {
  70. return;
  71. }
  72. loading = true;
  73. Map<String, String> params = Map();
  74. params['access_token'] = token;
  75. params['page'] = "$curPage";
  76. if (isHot) {
  77. params['user'] = "-1";
  78. } else {
  79. params['user'] = "0";
  80. }
  81. params['pageSize'] = "20";
  82. params['dataType'] = "json";
  83. NetUtils.get(Api.TWEETS_LIST, params: params).then((data) {
  84. Map<String, dynamic>? obj = json.decode(data);
  85. if (!isLoadMore) {
  86. // first load
  87. if (isHot) {
  88. hotTweetsList = obj!['tweetlist'];
  89. } else {
  90. normalTweetsList = obj!['tweetlist'];
  91. }
  92. } else {
  93. // load more
  94. List list = [];
  95. list.addAll(normalTweetsList!);
  96. list.addAll(obj!['tweetlist']);
  97. normalTweetsList = list;
  98. }
  99. filterList(hotTweetsList, true);
  100. filterList(normalTweetsList, false);
  101. });
  102. });
  103. }
  104. });
  105. }
  106. // 根据黑名单过滤出新的数组
  107. filterList(List<dynamic>? objList, bool isHot) {
  108. BlackListUtils.getBlackListIds().then((intList) {
  109. if (intList != null && intList.isNotEmpty && objList != null) {
  110. List newList = [];
  111. for (dynamic item in objList) {
  112. int? authorId = item['authorid'];
  113. if (!intList.contains(authorId)) {
  114. newList.add(item);
  115. }
  116. }
  117. setState(() {
  118. if (isHot) {
  119. hotTweetsList = newList;
  120. } else {
  121. normalTweetsList = newList;
  122. }
  123. loading = false;
  124. });
  125. } else {
  126. // 黑名单为空,直接返回原始数据
  127. setState(() {
  128. if (isHot) {
  129. hotTweetsList = objList;
  130. } else {
  131. normalTweetsList = objList;
  132. }
  133. loading = false;
  134. });
  135. }
  136. });
  137. }
  138. // 去掉文本中的html代码
  139. String clearHtmlContent(String str) {
  140. if (str.startsWith("<emoji")) {
  141. return "[emoji]";
  142. }
  143. var s = str.replaceAll(regExp1, "");
  144. s = s.replaceAll(regExp2, "");
  145. s = s.replaceAll("\n", "");
  146. return s;
  147. }
  148. Widget getRowWidget(Map<String, dynamic> listItem) {
  149. var authorRow = Row(
  150. children: [
  151. Container(
  152. width: 35.0,
  153. height: 35.0,
  154. decoration: BoxDecoration(
  155. shape: BoxShape.circle,
  156. color: Colors.transparent,
  157. image: DecorationImage(
  158. image: NetworkImage(listItem['portrait']),
  159. fit: BoxFit.cover),
  160. border: Border.all(
  161. color: Colors.white,
  162. width: 2.0,
  163. ),
  164. ),
  165. ),
  166. Padding(
  167. padding: const EdgeInsets.fromLTRB(6.0, 0.0, 0.0, 0.0),
  168. child: Text(listItem['author'],
  169. style: TextStyle(
  170. fontSize: 16.0,
  171. ))),
  172. Expanded(
  173. child: Row(
  174. mainAxisAlignment: MainAxisAlignment.end,
  175. children: [
  176. Text(
  177. '${listItem['commentCount']}',
  178. style: subtitleStyle,
  179. ),
  180. Image.asset(
  181. './images/ic_comment.png',
  182. width: 16.0,
  183. height: 16.0,
  184. )
  185. ],
  186. ),
  187. )
  188. ],
  189. );
  190. var _body = listItem['body'];
  191. _body = clearHtmlContent(_body);
  192. var contentRow = Row(
  193. children: [
  194. Expanded(
  195. child: Text(_body),
  196. )
  197. ],
  198. );
  199. var timeRow = Row(
  200. mainAxisAlignment: MainAxisAlignment.end,
  201. children: [
  202. Text(
  203. listItem['pubDate'],
  204. style: subtitleStyle,
  205. )
  206. ],
  207. );
  208. var columns = <Widget>[
  209. Padding(
  210. padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 2.0),
  211. child: authorRow,
  212. ),
  213. Padding(
  214. padding: const EdgeInsets.fromLTRB(52.0, 0.0, 10.0, 0.0),
  215. child: contentRow,
  216. ),
  217. ];
  218. String? imgSmall = listItem['imgSmall'];
  219. if (imgSmall != null && imgSmall.length > 0) {
  220. // 动弹中有图片
  221. List<String> list = imgSmall.split(",");
  222. List<String> imgUrlList = <String>[];
  223. for (String s in list) {
  224. if (s.startsWith("http")) {
  225. imgUrlList.add(s);
  226. } else {
  227. imgUrlList.add("https://static.oschina.net/uploads/space/" + s);
  228. }
  229. }
  230. List<Widget> imgList = [];
  231. List<List<Widget>> rows = [];
  232. num len = imgUrlList.length;
  233. for (var row = 0; row < getRow(len as int); row++) {
  234. List<Widget> rowArr = [];
  235. for (var col = 0; col < 3; col++) {
  236. num index = row * 3 + col;
  237. num screenWidth = MediaQuery.of(context).size.width;
  238. double cellWidth = (screenWidth - 100) / 3;
  239. if (index < len) {
  240. rowArr.add(Padding(
  241. padding: const EdgeInsets.all(2.0),
  242. child: Image.network(imgUrlList[index as int],
  243. width: cellWidth, height: cellWidth),
  244. ));
  245. }
  246. }
  247. rows.add(rowArr);
  248. }
  249. for (var row in rows) {
  250. imgList.add(Row(
  251. children: row,
  252. ));
  253. }
  254. columns.add(Padding(
  255. padding: const EdgeInsets.fromLTRB(52.0, 5.0, 10.0, 0.0),
  256. child: Column(
  257. children: imgList,
  258. ),
  259. ));
  260. }
  261. columns.add(Padding(
  262. padding: const EdgeInsets.fromLTRB(0.0, 10.0, 10.0, 6.0),
  263. child: timeRow,
  264. ));
  265. return InkWell(
  266. child: Column(
  267. children: columns,
  268. ),
  269. onTap: () {
  270. // 跳转到动弹详情
  271. Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
  272. return TweetDetailPage(
  273. tweetData: listItem,
  274. );
  275. }));
  276. },
  277. onLongPress: () {
  278. showDialog(
  279. context: context,
  280. builder: (BuildContext ctx) {
  281. return AlertDialog(
  282. title: Text('提示'),
  283. content: Text('要把\"${listItem['author']}\"关进小黑屋吗?'),
  284. actions: <Widget>[
  285. TextButton(
  286. child: Text(
  287. '取消',
  288. style: TextStyle(color: Colors.red),
  289. ),
  290. onPressed: () {
  291. Navigator.of(context).pop();
  292. },
  293. ),
  294. TextButton(
  295. child: Text(
  296. '确定',
  297. style: TextStyle(color: Colors.blue),
  298. ),
  299. onPressed: () {
  300. putIntoBlackHouse(listItem);
  301. },
  302. )
  303. ],
  304. );
  305. });
  306. },
  307. );
  308. }
  309. // 关进小黑屋
  310. putIntoBlackHouse(item) {
  311. int? authorId = item['authorid'];
  312. String portrait = "${item['portrait']}";
  313. String nickname = "${item['author']}";
  314. DataUtils.getUserInfo().then((info) {
  315. if (info != null) {
  316. int? loginUserId = info.id as int?;
  317. Map<String, String?> params = Map();
  318. params['userid'] = '$loginUserId';
  319. params['authorid'] = '$authorId';
  320. params['authoravatar'] = portrait;
  321. params['authorname'] = Utf8Utils.encode(nickname);
  322. NetUtils.post(Api.ADD_TO_BLACK, params: params).then((data) {
  323. Navigator.of(context).pop();
  324. if (data != null) {
  325. var obj = json.decode(data);
  326. if (obj['code'] == 0) {
  327. // 添加到小黑屋成功
  328. showAddBlackHouseResultDialog("添加到小黑屋成功!");
  329. BlackListUtils.addBlackId(authorId).then((arg) {
  330. // 添加之后,重新过滤数据
  331. filterList(normalTweetsList, false);
  332. filterList(hotTweetsList, true);
  333. });
  334. } else {
  335. // 添加失败
  336. var msg = obj['msg'];
  337. showAddBlackHouseResultDialog("添加到小黑屋失败:$msg");
  338. }
  339. }
  340. }).catchError((e) {
  341. Navigator.of(context).pop();
  342. showAddBlackHouseResultDialog("网络请求出错:$e");
  343. });
  344. }
  345. });
  346. }
  347. showAddBlackHouseResultDialog(String msg) {
  348. showDialog(
  349. context: context,
  350. builder: (BuildContext ctx) {
  351. return AlertDialog(
  352. title: Text('提示'),
  353. content: Text(msg),
  354. actions: <Widget>[
  355. TextButton(
  356. child: Text(
  357. '确定',
  358. style: TextStyle(color: Colors.red),
  359. ),
  360. onPressed: () {
  361. Navigator.of(context).pop();
  362. },
  363. )
  364. ],
  365. );
  366. });
  367. }
  368. renderHotRow(i) {
  369. if (i.isOdd) {
  370. return Divider(
  371. height: 1.0,
  372. );
  373. } else {
  374. i = i ~/ 2;
  375. return getRowWidget(hotTweetsList![i]);
  376. }
  377. }
  378. renderNormalRow(i) {
  379. if (i.isOdd) {
  380. return Divider(
  381. height: 1.0,
  382. );
  383. } else {
  384. i = i ~/ 2;
  385. return getRowWidget(normalTweetsList![i]);
  386. }
  387. }
  388. int getRow(int n) {
  389. int a = n % 3;
  390. int b = n ~/ 3;
  391. if (a != 0) {
  392. return b + 1;
  393. }
  394. return b;
  395. }
  396. Future<Null> _pullToRefresh() async {
  397. curPage = 1;
  398. getTweetsList(false, false);
  399. return null;
  400. }
  401. Widget getHotListView() {
  402. if (hotTweetsList == null) {
  403. getTweetsList(false, true);
  404. return Center(
  405. child: CircularProgressIndicator(),
  406. );
  407. } else {
  408. // 热门动弹列表
  409. return ListView.builder(
  410. itemCount: hotTweetsList!.length * 2 - 1,
  411. itemBuilder: (context, i) => renderHotRow(i),
  412. );
  413. }
  414. }
  415. Widget getNormalListView() {
  416. if (normalTweetsList == null) {
  417. getTweetsList(false, false);
  418. return Center(
  419. child: CircularProgressIndicator(),
  420. );
  421. } else {
  422. // 普通动弹列表
  423. return RefreshIndicator(
  424. child: ListView.builder(
  425. itemCount: normalTweetsList!.length * 2 - 1,
  426. itemBuilder: (context, i) => renderNormalRow(i),
  427. physics: const AlwaysScrollableScrollPhysics(),
  428. controller: _controller,
  429. ),
  430. onRefresh: _pullToRefresh);
  431. }
  432. }
  433. @override
  434. Widget build(BuildContext context) {
  435. if (!isUserLogin) {
  436. return Center(
  437. child: Column(
  438. mainAxisAlignment: MainAxisAlignment.center,
  439. children: [
  440. Container(
  441. padding: const EdgeInsets.all(10.0),
  442. child: Center(
  443. child: Column(
  444. children: [
  445. Text("由于OSC的openapi限制"),
  446. Text("必须登录后才能获取动弹信息")
  447. ],
  448. ),
  449. )
  450. ),
  451. InkWell(
  452. child: Container(
  453. padding: const EdgeInsets.fromLTRB(15.0, 8.0, 15.0, 8.0),
  454. child: Text("去登录"),
  455. decoration: BoxDecoration(
  456. border: Border.all(color: Colors.black),
  457. borderRadius: BorderRadius.all(Radius.circular(5.0))
  458. ),
  459. ),
  460. onTap: () async {
  461. final result = await Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
  462. return LoginPage();
  463. }));
  464. if (result != null && result == "refresh") {
  465. // 通知动弹页面刷新
  466. Constants.eventBus.fire(LoginEvent());
  467. }
  468. },
  469. ),
  470. ],
  471. ),
  472. );
  473. }
  474. return DefaultTabController(
  475. length: 2,
  476. child: Scaffold(
  477. appBar: TabBar(
  478. tabs: <Widget>[
  479. Tab(
  480. text: "动弹列表",
  481. ),
  482. Tab(
  483. text: "热门动弹",
  484. )
  485. ],
  486. ),
  487. body: TabBarView(
  488. children: [getNormalListView(), getHotListView()],
  489. )),
  490. );
  491. }
  492. }