基础组件库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

442 lines
14 KiB

  1. import 'dart:convert';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:pull_to_refresh/pull_to_refresh.dart';
  5. import 'package:tab_indicator_styler/tab_indicator_styler.dart';
  6. import 'package:zhiying_base_widget/pages/custom_page/custom_item_page.dart';
  7. import 'package:zhiying_base_widget/pages/main_page/model/background_model.dart';
  8. import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_bg_notifier.dart';
  9. import 'package:zhiying_base_widget/widgets/custom/search/custom_search_widget.dart';
  10. import 'package:zhiying_base_widget/widgets/empty/empty_widget.dart';
  11. import 'package:zhiying_base_widget/widgets/others/mine_header_bg_widget.dart';
  12. import 'package:zhiying_comm/zhiying_comm.dart';
  13. import 'package:flutter/material.dart';
  14. import 'package:provider/provider.dart';
  15. import 'package:flutter_bloc/flutter_bloc.dart';
  16. import 'bloc/background_bloc.dart';
  17. import 'bloc/custom_page_bloc.dart';
  18. import 'bloc/custom_page_state.dart';
  19. import 'bloc/custom_page_event.dart';
  20. import 'bloc/custom_page_repository.dart';
  21. import 'dart:ui';
  22. import 'package:fluttertoast/fluttertoast.dart';
  23. ///
  24. /// 通用模块页面
  25. ///
  26. class CustomPage extends StatefulWidget {
  27. final Map<String, dynamic> data;
  28. CustomPage(this.data, {Key key}) : super(key: key);
  29. @override
  30. _CustomPageState createState() => _CustomPageState();
  31. }
  32. class _CustomPageState extends State<CustomPage> {
  33. @override
  34. Widget build(BuildContext context) {
  35. Logger.log("数据: " + widget?.data.toString());
  36. return MultiProvider(
  37. providers: [
  38. ChangeNotifierProvider.value(value: MainPageBgNotifier()),
  39. ],
  40. child: BlocProvider<CustomPageBloc>(
  41. create: (_) => CustomPageBloc(CustomPageRepository(data: widget?.data))..add(CustomPageInitEvent()),
  42. child: _CommonPageContainer(widget?.data),
  43. // ),
  44. ),
  45. );
  46. }
  47. }
  48. class _CommonPageContainer extends StatefulWidget {
  49. final Map<String, dynamic> data;
  50. _CommonPageContainer(this.data);
  51. @override
  52. __CommonPageContainerState createState() => __CommonPageContainerState();
  53. }
  54. class __CommonPageContainerState extends State<_CommonPageContainer> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  55. TabController _tabController;
  56. // 是否有AppBar
  57. bool _isHasAppbar = false;
  58. // 是否有TabBar
  59. bool _isHasTabBar = false;
  60. double backgroundTopMargin = 0;
  61. BackgroundBloc backgroundBloc;
  62. /// 刷新
  63. void _onRefreshEvent() async {
  64. BlocProvider.of<CustomPageBloc>(context).add(CustomPageRefreshEvent());
  65. }
  66. @override
  67. void initState() {
  68. backgroundBloc = BackgroundBloc();
  69. super.initState();
  70. }
  71. @override
  72. void dispose() {
  73. _tabController?.dispose();
  74. backgroundBloc.streamController.close();
  75. super.dispose();
  76. }
  77. @override
  78. Widget build(BuildContext context) {
  79. SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
  80. return BlocConsumer<CustomPageBloc, CustomPageState>(
  81. listener: (context, state) {},
  82. buildWhen: (prev, current) {
  83. if (current is CustomPageErrorState) {
  84. return false;
  85. }
  86. if (current is CustomPageRefreshSuccessState) {
  87. // _refreshController.refreshCompleted(resetFooterState: true);
  88. return false;
  89. }
  90. if (current is CustomPageRefreshErrorState) {
  91. // _refreshController.refreshFailed();
  92. return false;
  93. }
  94. return true;
  95. },
  96. builder: (context, state) {
  97. /// 有数据
  98. if (state is CustomPageLoadedState) {
  99. if (EmptyUtil.isEmpty(state.model)) return _buildEmptyWidget();
  100. Logger.log("通用模板数据", state.model);
  101. return _buildMainWidget(state.model, state.backgroundModel);
  102. }
  103. /// 初始化失败
  104. if (state is CustomPageInitErrorState) {
  105. return _buildEmptyWidget();
  106. }
  107. /// 骨架图
  108. return _buildSkeletonWidget();
  109. },
  110. );
  111. }
  112. /// 有数据
  113. Widget _buildMainWidget(List<Map<String, dynamic>> model, BackgroundModel backgroundModel) {
  114. return Scaffold(
  115. appBar: _buildAppbar(model?.first),
  116. backgroundColor: HexColor.fromHex(backgroundModel?.bgColor == null || backgroundModel?.bgColor == '' ? "#FFF9F9F9" : backgroundModel?.bgColor ?? "#FFF9F9F9"),
  117. // floatingActionButton: _buildFloatWidget(),
  118. floatingActionButtonLocation: _CustomFloatingActionButtonLocation(FloatingActionButtonLocation.endFloat, 0, -100),
  119. body: Stack(
  120. children: <Widget>[
  121. _buildBackground(backgroundModel),
  122. Column(children: _buildFirstWidget(model, backgroundModel)),
  123. ],
  124. ),
  125. );
  126. }
  127. /// 骨架图
  128. Widget _buildSkeletonWidget() {
  129. return Scaffold();
  130. }
  131. /// 空数据视图
  132. Widget _buildEmptyWidget() {
  133. return Scaffold(
  134. backgroundColor: HexColor.fromHex('#F9F9F9'),
  135. appBar: AppBar(
  136. brightness: Brightness.light,
  137. backgroundColor: Colors.white,
  138. leading: IconButton(
  139. icon: Icon(
  140. Icons.arrow_back_ios,
  141. size: 22,
  142. color: HexColor.fromHex('#333333'),
  143. ),
  144. onPressed: () => Navigator.maybePop(context),
  145. ),
  146. title: Text(
  147. '',
  148. style: TextStyle(color: HexColor.fromHex('#333333'), fontSize: 18, fontWeight: FontWeight.bold),
  149. ),
  150. centerTitle: true,
  151. elevation: 0,
  152. ),
  153. body: Column(
  154. crossAxisAlignment: CrossAxisAlignment.center,
  155. mainAxisAlignment: MainAxisAlignment.center,
  156. children: <Widget>[
  157. Align(
  158. alignment: Alignment.topCenter,
  159. child: EmptyWidget(
  160. tips: '网络似乎开小差了~',
  161. ),
  162. ),
  163. GestureDetector(
  164. onTap: () => _onRefreshEvent(),
  165. behavior: HitTestBehavior.opaque,
  166. child: Container(
  167. alignment: Alignment.center,
  168. decoration: BoxDecoration(borderRadius: BorderRadius.circular(10), border: Border.all(color: HexColor.fromHex('#999999'), width: 0.5), color: Colors.white),
  169. width: 80,
  170. height: 20,
  171. child: Text(
  172. '刷新一下',
  173. style: TextStyle(fontSize: 12, color: HexColor.fromHex('#333333'), fontWeight: FontWeight.bold),
  174. ),
  175. ),
  176. )
  177. ],
  178. ));
  179. }
  180. /// 数据,生成第一层widget
  181. List<Widget> _buildFirstWidget(List<Map<String, dynamic>> model, BackgroundModel backgroundModel) {
  182. List<Widget> result = [];
  183. // 分类导航的key ⚠️ 这里先写成Test 后续要改
  184. const String CATEGORY_KEY = 'category';
  185. // 判断是否有分类导航
  186. // 判断最后一个是否属于分类导航,如果属于,则有分类导航,如果不是,则无分类导航
  187. bool haveCategory = !EmptyUtil.isEmpty(model?.last) && model.last.containsKey('mod_name') && model.last['mod_name'] == CATEGORY_KEY;
  188. int endIndexLength = model.length;
  189. // 如果没有分类导航,则取分类导航之上的所有mod
  190. if (!haveCategory) {
  191. for (int i = 0; i < model.length; i++) {
  192. Map<String, dynamic> item = model[i];
  193. if (item['mod_name'] == CATEGORY_KEY) {
  194. endIndexLength = (i + 1);
  195. break;
  196. }
  197. }
  198. }
  199. for (int i = 0; i < endIndexLength; i++) {
  200. WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(model[i]));
  201. // last model
  202. if (i == endIndexLength - 1) {
  203. result.addAll(_buildTabBar(model[i], i));
  204. break;
  205. }
  206. // appBar 无需在这里添加
  207. if (item.modName.contains('appbar')) {
  208. continue;
  209. }
  210. result.addAll(WidgetFactory.create(item.modName, isSliver: false, model: model[i]));
  211. }
  212. // 没有appbar并且没有tabbar,则给第一个元素加边距
  213. if (!_isHasAppbar) {
  214. result.insert(0, SizedBox(height: MediaQueryData.fromWindow(window).padding.top, child: Container(color: HexColor.fromHex(backgroundModel?.headerBg?.mainColor))));
  215. }
  216. return result;
  217. }
  218. /// appbar
  219. Widget _buildAppbar(final Map<String, dynamic> model) {
  220. if (EmptyUtil.isEmpty(model)) return null;
  221. String mobName = model['mod_name'];
  222. if (!mobName.contains('_appbar')) return null;
  223. Map<String, dynamic> data = Map<String, dynamic>();
  224. try {
  225. data = jsonDecode(model['data']);
  226. } catch (e, s) {
  227. Logger.warn(e, s);
  228. }
  229. String parentTitle = !EmptyUtil.isEmpty(widget?.data) ? widget?.data['title'] ?? '' : '';
  230. _isHasAppbar = true;
  231. return AppBar(
  232. backgroundColor: HexColor.fromHex(null != data ? data['app_bar_bg_color'] ?? '#FFFFFF' : '#FFFFFF'),
  233. brightness: Brightness.light,
  234. leading: IconButton(
  235. icon: Icon(
  236. Icons.arrow_back_ios,
  237. size: 22,
  238. color: HexColor.fromHex('#333333'),
  239. ),
  240. onPressed: () => Navigator.maybePop(context),
  241. ),
  242. title: Text(
  243. null != data && data.containsKey('app_bar_name')
  244. ? data['app_bar_name'] != '自定义页面'
  245. ? data['app_bar_name']
  246. : parentTitle
  247. : parentTitle,
  248. style: TextStyle(
  249. color: HexColor.fromHex(null != data ? data['app_bar_name_color'] ?? '#333333' : '#333333'),
  250. fontSize: 16,
  251. fontWeight: FontWeight.bold,
  252. ),
  253. ),
  254. centerTitle: true,
  255. elevation: 0,
  256. );
  257. }
  258. /// tabBar
  259. List<Widget> _buildTabBar(final Map<String, dynamic> model, final int index) {
  260. Map<String, dynamic> data = Map<String, dynamic>();
  261. List<Map<String, dynamic>> listStyle = [];
  262. List<Widget> result = [];
  263. try {
  264. data = jsonDecode(model['data']);
  265. listStyle = List.from(data['list_style']);
  266. } catch (e, s) {
  267. Logger.warn(e, s);
  268. }
  269. // 1、导航栏没开启的情况 传null进去进行获取没开启导航栏的widget集合
  270. if (EmptyUtil.isEmpty(listStyle)) {
  271. result.add(Expanded(
  272. child: CustomItemPage(
  273. null,
  274. 0,
  275. model['mod_id']?.toString() ?? null,
  276. model['mod_pid']?.toString() ?? null,
  277. (!_isHasAppbar && index == 0),
  278. scroller: _listenScroller,
  279. ),
  280. ));
  281. return result;
  282. }
  283. // 2、导航栏开启的情况
  284. if (listStyle.length > 0) {
  285. // tabContorller 初始化
  286. if (null == _tabController || _tabController.length != listStyle.length) {
  287. _tabController = new TabController(length: listStyle.length, vsync: this);
  288. }
  289. result.add(Container(
  290. height: 40,
  291. width: double.infinity,
  292. color: HexColor.fromHex(data['bg_color']),
  293. child: TabBar(
  294. controller: _tabController,
  295. isScrollable: /*listStyle.length <= 5 ? false : */ true,
  296. labelColor: HexColor.fromHex(data['choose_text_color'] ?? '#FF4242'),
  297. labelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
  298. unselectedLabelColor: HexColor.fromHex(data['text_color'] ?? '#999999'),
  299. unselectedLabelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
  300. indicatorSize: TabBarIndicatorSize.label,
  301. indicator: MaterialIndicator(
  302. color: HexColor.fromHex(data['choose_color'] ?? '#FF4242'),
  303. bottomLeftRadius: 1.25,
  304. topLeftRadius: 1.25,
  305. topRightRadius: 1.25,
  306. bottomRightRadius: 1.25,
  307. height: 2.5,
  308. horizontalPadding: 5,
  309. ),
  310. tabs: listStyle.map((e) => Text(e['name'])).toList(),
  311. ),
  312. ));
  313. _isHasTabBar = true;
  314. // 最后添加TabBarView
  315. result.add(Expanded(
  316. child: TabBarView(
  317. controller: _tabController,
  318. children: _buildTabBarViewChildren(listStyle, model['mod_id']?.toString(), model['mod_pid']?.toString(), index),
  319. ),
  320. ));
  321. }
  322. return result;
  323. }
  324. /// 返回TabBarView的视图
  325. List<Widget> _buildTabBarViewChildren(final List<Map<String, dynamic>> listStyle, final String modId, final String modPid, final int index) {
  326. List<Widget> result = [];
  327. for (int i = 0; i < listStyle.length; i++) {
  328. result.add(CustomItemPage(
  329. listStyle[i],
  330. i,
  331. modId,
  332. modPid,
  333. (!_isHasAppbar && !_isHasTabBar && index == 0),
  334. scroller: _listenScroller,
  335. ));
  336. }
  337. return result;
  338. }
  339. _buildBackground(BackgroundModel backgroundModel) {
  340. if (backgroundModel != null) {
  341. var headerBg = backgroundModel.headerBg;
  342. return StreamBuilder(
  343. stream: backgroundBloc.outData,
  344. builder: (context, asncy) {
  345. return Container(
  346. constraints: BoxConstraints(minHeight: 0),
  347. height: (double.tryParse(headerBg?.height) ?? 0) + backgroundTopMargin ?? 0,
  348. width: double.infinity,
  349. decoration: BoxDecoration(
  350. gradient: LinearGradient(
  351. begin: Alignment.topCenter,
  352. end: Alignment.bottomCenter,
  353. colors: [HexColor.fromHex(headerBg?.mainColor ?? ""), HexColor.fromHex(headerBg?.assistColor ?? ""), HexColor.fromHex(headerBg?.minorColor ?? "")])),
  354. );
  355. },
  356. );
  357. } else {
  358. return Container();
  359. }
  360. }
  361. // /// 悬浮按钮
  362. // Widget _buildFloatWidget() {
  363. // return Visibility(
  364. // visible: true,
  365. // child: GestureDetector(
  366. // onTap: () => _scrollTop(),
  367. // behavior: HitTestBehavior.opaque,
  368. // child: Container(
  369. // height: 30,
  370. // width: 30,
  371. // child: Icon(Icons.arrow_upward),
  372. // ),
  373. // ),
  374. // );
  375. // }
  376. ///监听页面滚动
  377. _listenScroller(double offset) {
  378. if (offset >= 0) {
  379. backgroundTopMargin = -offset;
  380. if (backgroundTopMargin > -500) {
  381. backgroundBloc.streamController.add("");
  382. }
  383. }
  384. }
  385. @override
  386. // TODO: implement wantKeepAlive
  387. bool get wantKeepAlive => true;
  388. }
  389. /// 回到顶部的icon
  390. class _CustomFloatingActionButtonLocation extends FloatingActionButtonLocation {
  391. FloatingActionButtonLocation location;
  392. double offsetX; // X方向的偏移量
  393. double offsetY; // Y方向的偏移量
  394. _CustomFloatingActionButtonLocation(this.location, this.offsetX, this.offsetY);
  395. @override
  396. Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
  397. Offset offset = location.getOffset(scaffoldGeometry);
  398. return Offset(offset.dx + offsetX, offset.dy + offsetY);
  399. }
  400. }