mind_map_index.dart 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter_slidable/flutter_slidable.dart';
  3. import 'package:o2_flutter/common/routers/application.dart';
  4. import '../../common/models/mindmap/mind_folder.dart';
  5. import '../../common/models/mindmap/mind_map.dart';
  6. import '../../common/models/mindmap/mind_node.dart';
  7. import '../../common/utils/o2_api_manager.dart';
  8. import '../../common/utils/x_mind_assemble_control.dart';
  9. import '../../common/widgets/bottom_sheet_helper.dart';
  10. import '../../common/widgets/dialogs.dart';
  11. import '../../common/widgets/final_widget.dart';
  12. import '../../common/widgets/loading.dart';
  13. import '../../common/widgets/mind_map_end_float_location.dart';
  14. import '../../common/widgets/snack_bars.dart';
  15. import '../../common/widgets/system_pop_app_bar.dart';
  16. import '../../o2.dart';
  17. import 'mind_map_data.dart';
  18. class MindMapHomePage extends StatefulWidget {
  19. const MindMapHomePage({Key? key}) : super(key: key);
  20. @override
  21. _MindMapHomePageState createState() => _MindMapHomePageState();
  22. }
  23. class _MindMapHomePageState extends State<MindMapHomePage>
  24. with SingleTickerProviderStateMixin {
  25. final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
  26. ScrollController _scrollController = ScrollController(); //listview的控制器
  27. TextEditingController? newFolderEditingController;
  28. AnimationController? animationController;
  29. Animation<double>? animation;
  30. List<MindMap> _datas = [];
  31. List<MindFolder> _trees = [];
  32. bool _isFirstLoading = true;
  33. String _folderName = '根目录';
  34. String _folderId = 'root';
  35. String _lastPageId = firstPageId;
  36. void _getFolderTree() {
  37. _trees.clear();
  38. MindMapService().myFolderTree().then((list) {
  39. //查询到tree转化成list
  40. Map<String, dynamic> json = Map();
  41. json['name'] = '根目录';
  42. json['id'] = 'root';
  43. MindFolder root = MindFolder.fromJson(json);
  44. root.level = 1;
  45. _trees.add(root);
  46. _recursionTree(list, 2);
  47. // 刷新选中目录的名称
  48. _trees.forEach((tree) {
  49. if (tree.id == _folderId) {
  50. _folderName = tree.name ?? '根目录';
  51. }
  52. });
  53. setState(() {});
  54. }).catchError((error) {
  55. print(error);
  56. setState(() {});
  57. });
  58. }
  59. void _recursionTree(List<MindFolder> children, int level) {
  60. if (children.isEmpty) {
  61. return;
  62. }
  63. for (var tree in children) {
  64. tree.level = level;
  65. _trees.add(tree);
  66. if (tree.children != null && tree.children!.isNotEmpty) {
  67. _recursionTree(tree.children!, level + 1);
  68. }
  69. }
  70. }
  71. void _getData() {
  72. _lastPageId = firstPageId;
  73. _datas.clear();
  74. _fetchData();
  75. }
  76. void _getMore() {
  77. if (_datas.isNotEmpty) {
  78. _lastPageId = _datas.last.id ?? firstPageId;
  79. _fetchData();
  80. } else {
  81. print('没有更多数据了。。。。。。。。。。');
  82. }
  83. }
  84. void _fetchData() {
  85. MindMapService().mindFilterByPage(_lastPageId, _folderId).then((list) {
  86. if (list != null && list.isNotEmpty) {
  87. _datas.addAll(list);
  88. }
  89. setState(() {
  90. _isFirstLoading = false;
  91. });
  92. }).catchError((error) {
  93. print(error);
  94. setState(() {
  95. _isFirstLoading = false;
  96. });
  97. _showErrorSnap('获取数据异常!');
  98. });
  99. }
  100. void _changeFolder(int index) {
  101. _folderId = _trees[index].id!;
  102. _folderName = _trees[index].name!;
  103. _getData();
  104. }
  105. void _newOrEditFolder(String parentId, String? id) {
  106. var folderName = newFolderEditingController?.text;
  107. if (folderName == null || folderName.trim().isEmpty) {
  108. _showErrorSnap('目录名称不能为空!');
  109. } else {
  110. Loading.start(context);
  111. MindMapService().saveMindFolder(folderName, parentId, id: id).then((id) {
  112. Loading.complete(context);
  113. _getFolderTree();
  114. }).catchError((error) {
  115. print(error);
  116. Loading.complete(context);
  117. _showErrorSnap(id == null ? '新建目录失败!' : '修改目录失败!');
  118. });
  119. }
  120. }
  121. ///
  122. /// 删除目录
  123. /// 先判断是否有子目录,然后查询是否有文件 ,全都没有才能删除
  124. ///
  125. void _deleteFolderValidate(int index) async {
  126. MindFolder deleteFolder = _trees[index];
  127. bool hasSubFolder = true;
  128. if (index + 1 < _trees.length) {
  129. MindFolder next = _trees[index + 1];
  130. if (deleteFolder.level! < next.level!) {
  131. //是子目录
  132. _showErrorSnap('无法删除,请先删除当前目录的子目录和文件!');
  133. } else {
  134. hasSubFolder = false;
  135. }
  136. } else {
  137. hasSubFolder = false;
  138. }
  139. if (!hasSubFolder) {
  140. List<MindMap> list =
  141. await MindMapService().mindFilterByPage(firstPageId, deleteFolder.id!);
  142. if (list.isNotEmpty) {
  143. _showErrorSnap('无法删除,请先删除当前目录下的所有文件!');
  144. } else {
  145. O2Dialogs.showConfirmDialog(message: '确定要删除这个目录?', context: context)
  146. .then((result) {
  147. if (result == O2DialogAction.positive) {
  148. _deleteFolder(index);
  149. }
  150. });
  151. }
  152. }
  153. }
  154. void _deleteFolder(int index) async {
  155. MindFolder deleteFolder = _trees[index];
  156. bool result = await MindMapService().deleteMindFolder(deleteFolder.id!);
  157. if (result) {
  158. if (_folderId == deleteFolder.id) {
  159. _changeFolder(0);
  160. }
  161. setState(() {
  162. _trees.removeAt(index);
  163. });
  164. }
  165. }
  166. ///新建脑图
  167. void _newMindMap() async {
  168. var mindName = newFolderEditingController?.text;
  169. if (mindName == null || mindName.trim().isEmpty) {
  170. _showErrorSnap('脑图名称不能为空!');
  171. } else {
  172. Loading.start(context);
  173. Node node = Node(data: NodeData(text: mindName), children: []);
  174. Map<String, dynamic> dataJson = {};
  175. dataJson['root'] = node.toJson();
  176. dataJson['template'] = 'default';
  177. dataJson['theme'] = 'fresh-blue';
  178. MindMapData data = MindMapData.fromJson(dataJson);
  179. Map<String, dynamic> mindJson = {};
  180. mindJson['name'] = mindName;
  181. mindJson['folderId'] = _folderId;
  182. mindJson['fileVersion'] = 0;
  183. MindMap map = MindMap.fromJson(mindJson);
  184. MindMapService().saveMindMap(map, data).then((id) {
  185. if (id.isNotEmpty) {
  186. map.id = id;
  187. _datas.add(map);
  188. Loading.complete(context);
  189. setState(() {
  190. _gotoMindMapView(_datas.length - 1);
  191. });
  192. }
  193. }).catchError((error) {
  194. print('新建脑图异常$error');
  195. Loading.complete(context);
  196. _showErrorSnap('新建脑图失败!');
  197. });
  198. }
  199. }
  200. void _renameMindMap(MindMap map) {
  201. newFolderEditingController?.text = map.name ?? '';
  202. O2Dialogs.showCustomDialog(
  203. context: context,
  204. title: '重命名脑图',
  205. content: TextField(
  206. controller: newFolderEditingController,
  207. autofocus: true,
  208. decoration:
  209. const InputDecoration(labelText: '名称', hintText: '请输入脑图名称'),
  210. )).then((action) {
  211. if (action == O2DialogAction.positive) {
  212. _renameMindMap2Remote(map);
  213. }
  214. });
  215. }
  216. ///新建脑图
  217. void _renameMindMap2Remote(MindMap map) async {
  218. var mindName = newFolderEditingController?.text;
  219. if (mindName == null || mindName.trim().isEmpty) {
  220. _showErrorSnap('脑图名称不能为空!');
  221. } else {
  222. map.name = mindName;
  223. var allMindMapData = await MindMapService().mindMap(map.id!); //要重新get一下 不然content没有内容
  224. allMindMapData.name = mindName;
  225. MindMapService().renameMindMap(allMindMapData).then((id) {
  226. if (id.isNotEmpty) {
  227. setState(() {
  228. print('更新了脑图名称。。。。。。。。');
  229. });
  230. }
  231. }).catchError((error) {
  232. print('更新脑图异常$error');
  233. _showErrorSnap('更新脑图失败!');
  234. });
  235. }
  236. }
  237. void _deleteMindMap(MindMap map) {
  238. O2Dialogs.showConfirmDialog(
  239. message: '确定要删除这个脑图,名称:【${map.name}】?', context: context)
  240. .then((result) {
  241. if (result == O2DialogAction.positive) {
  242. MindMapService().deleteMindMap(map.id!).then((result) {
  243. if (!result) {
  244. print('删除失败');
  245. }
  246. _getData();
  247. }).catchError((error) {
  248. print('删除脑图出错,$error');
  249. _showErrorSnap('删除脑图出错!');
  250. });
  251. }
  252. });
  253. }
  254. void _gotoMindMapView(int index) async {
  255. print('点了第$index行。。。。。。。打开脑图编辑器');
  256. await AppRouterManager.instance.router?.navigateTo(context, '/mindMap/${_datas[index].id}');
  257. print('返回了。。。。刷新数据');
  258. _getData();
  259. }
  260. @override
  261. void initState() {
  262. super.initState();
  263. newFolderEditingController = TextEditingController();
  264. animationController =
  265. AnimationController(duration: const Duration(milliseconds: 300), vsync: this);
  266. animation = Tween<double>(begin: 64, end: 400).animate(animationController!)
  267. ..addListener(() {
  268. setState(() {});
  269. });
  270. _getFolderTree();
  271. _getData();
  272. _scrollController.addListener(() {
  273. if (_scrollController.position.pixels ==
  274. _scrollController.position.maxScrollExtent) {
  275. _getMore();
  276. }
  277. });
  278. }
  279. @override
  280. void dispose() {
  281. animationController?.dispose();
  282. super.dispose();
  283. }
  284. @override
  285. Widget build(BuildContext context) {
  286. return Scaffold(
  287. key: _scaffoldKey,
  288. appBar: systemPopAppBar('脑图'),
  289. body: _buildBody(),
  290. floatingActionButtonLocation: MindMapFloatingActionButtonLocation(),
  291. floatingActionButton: FloatingActionButton(
  292. onPressed: _showAddMenu,
  293. tooltip: '新建',
  294. child: const Icon(Icons.add),
  295. ), // This trailing comma makes auto-formatting nicer for build methods.
  296. );
  297. }
  298. Widget _buildBody() {
  299. if (_isFirstLoading) {
  300. return const Center(child: CircularProgressIndicator());
  301. } else {
  302. return Column(
  303. children: <Widget>[
  304. Expanded(
  305. child: _datas.length > 0 ? _gridView() : _emptyDataView(),
  306. ),
  307. _bottomFolderBar()
  308. ],
  309. );
  310. }
  311. }
  312. //grid 列表
  313. Widget _gridView() {
  314. return Padding(
  315. padding: EdgeInsets.all(5),
  316. child: GridView.builder(
  317. controller: _scrollController,
  318. itemCount: _datas.length,
  319. gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  320. crossAxisCount: 2, mainAxisSpacing: 5, crossAxisSpacing: 5),
  321. itemBuilder: _gridItemView));
  322. }
  323. Widget _gridItemView(BuildContext context, int index) {
  324. MindMap data = _datas[index];
  325. return InkWell(
  326. child: GridTile(
  327. child: Container(
  328. height: 144,
  329. color: o2Dark,
  330. child: FadeInImage.assetNetwork(
  331. placeholder: 'images/default_image.png',
  332. image: O2ApiManager.instance.getFileURL(data.icon)),
  333. ),
  334. footer: Container(
  335. height: 40,
  336. decoration: BoxDecoration(
  337. border: Border.all(color: O2UI.dividerColor),
  338. color: Colors.white),
  339. child: Row(
  340. crossAxisAlignment: CrossAxisAlignment.center,
  341. mainAxisAlignment: MainAxisAlignment.center,
  342. children: <Widget>[
  343. Expanded(
  344. flex: 1,
  345. child: Padding(
  346. padding: const EdgeInsets.fromLTRB(8, 0, 0, 0),
  347. child: Text(data.name ?? '', style: O2UI.primaryTextStyle),
  348. ),
  349. ),
  350. IconButton(
  351. icon: const Icon(Icons.more_vert),
  352. onPressed: ()=>_showMindMapOperationMenu(data),
  353. )
  354. ],
  355. ),
  356. ),
  357. ),
  358. onTap: () {
  359. _gotoMindMapView(index);
  360. },
  361. );
  362. }
  363. //列表
  364. Widget _listView() {
  365. return ListView.separated(
  366. controller: _scrollController,
  367. itemBuilder: _itemView,
  368. separatorBuilder: _separatorView,
  369. itemCount: _datas.length);
  370. }
  371. //列表项外框和点击事件
  372. Widget _itemView(BuildContext context, int index) {
  373. return InkWell(
  374. child: _slideRow(index, _datas[index]),
  375. onTap: () {
  376. _gotoMindMapView(index);
  377. },
  378. );
  379. }
  380. //列表项滑动控件
  381. Widget _slideRow(int index, MindMap data) {
  382. return Slidable(
  383. // The end action pane is the one at the right or the bottom side.
  384. endActionPane: ActionPane(
  385. motion: const ScrollMotion(),
  386. children: [
  387. SlidableAction(
  388. onPressed: (_) {
  389. _deleteMindMap(_datas[index]);
  390. },
  391. backgroundColor: Colors.red,
  392. foregroundColor: Colors.white,
  393. icon: Icons.delete,
  394. label: '删除',
  395. ),
  396. ],
  397. ),
  398. child: _rowContentView(data),
  399. );
  400. }
  401. //列表项内容
  402. Widget _rowContentView(MindMap data) {
  403. return ListTile(
  404. leading: Container(
  405. width: 48,
  406. height: 48,
  407. color: o2Dark,
  408. child: FadeInImage.assetNetwork(
  409. placeholder: 'images/default_image.png',
  410. image: O2ApiManager.instance.getFileURL(data.icon),
  411. width: 48,
  412. height: 48,
  413. ),
  414. ),
  415. title: Text(data.name ?? '', style: O2UI.primaryTextStyle),
  416. subtitle: Text('版本:${data.fileVersion}', style: O2UI.hintTextStyle),
  417. trailing:
  418. Text(_timeFormat(data.updateTime), style: O2UI.hintTextStyle),
  419. );
  420. }
  421. ///
  422. /// @param time 2019-02-11 12:20:00
  423. String _timeFormat(String?time) {
  424. if (time!=null && time.isNotEmpty && time.length > 16) {
  425. var year = time.substring(0, 4);
  426. if (DateTime.now().year == int.parse(year)) {
  427. return time.substring(5, 16);
  428. } else {
  429. return time.substring(0, 16);
  430. }
  431. } else {
  432. return "";
  433. }
  434. }
  435. //分割线
  436. Widget _separatorView(BuildContext context, int index) {
  437. return O2UI.separatorView;
  438. }
  439. // 没有数据的时候显示的文字
  440. Widget _emptyDataView() {
  441. return const Center(child: Text('空空如也!', style: O2UI.hintTextStyle));
  442. }
  443. // 底部 文件夹 栏
  444. Widget _bottomFolderBar() {
  445. var screenWidth = MediaQuery.of(context).size.width;
  446. return SizedBox(
  447. height: animation!.value,
  448. child: Stack(
  449. children: <Widget>[
  450. Positioned(
  451. left: 0,
  452. top: 0,
  453. width: screenWidth,
  454. height: 400,
  455. child: Column(
  456. children: <Widget>[
  457. _bottomFolderBarHeader(),
  458. Expanded(
  459. child: Container(
  460. child: _bottomFolderListView(),
  461. ),
  462. )
  463. ],
  464. ))
  465. ],
  466. ));
  467. }
  468. Widget _bottomFolderBarHeader() {
  469. return InkWell(
  470. onTap: () {
  471. if (animation!.value > 64) {
  472. animationController?.reverse();
  473. } else {
  474. animationController?.forward();
  475. }
  476. },
  477. child: Container(
  478. padding: const EdgeInsets.all(16),
  479. color: O2UI.backgroundColor,
  480. child: Row(
  481. children: <Widget>[
  482. const Icon(Icons.folder, color: O2UI.iconColor, size: 32),
  483. Expanded(
  484. child: Align(
  485. alignment: Alignment.center,
  486. child: Text(_folderName, style: O2UI.primaryTextStyle),
  487. ),
  488. ),
  489. animation!.value > 64
  490. ? const Icon(Icons.arrow_drop_down, color: O2UI.iconColor, size: 32)
  491. : const Icon(Icons.arrow_drop_up, color: O2UI.iconColor, size: 32)
  492. ],
  493. ),
  494. ),
  495. );
  496. }
  497. Widget _bottomFolderListView() {
  498. return ListView.builder(
  499. itemBuilder: _folderItemView,
  500. itemCount: _trees.length,
  501. );
  502. }
  503. Widget _folderItemView(BuildContext context, int index) {
  504. return InkWell(
  505. onTap: () {
  506. _changeFolder(index);
  507. animationController?.reverse();
  508. },
  509. child: Slidable(
  510. endActionPane: ActionPane(
  511. motion: ScrollMotion(),
  512. children: _folderSlideMenu(index),
  513. ),
  514. child: ListTile(
  515. contentPadding:
  516. EdgeInsets.fromLTRB(16.0 + (_trees[index].level??0 * 8.0), 0, 16, 0),
  517. title: Text(_trees[index].name ?? ''),
  518. selected: _trees[index].id == _folderId,
  519. )
  520. ),
  521. );
  522. }
  523. ///
  524. /// 目录列表横拉菜单
  525. ///
  526. List<Widget> _folderSlideMenu(int index) {
  527. if (index == 0) {
  528. return [];
  529. } else {
  530. return <Widget>[
  531. SlidableAction(
  532. onPressed: (_) {
  533. print('删除目录。。。。。。。。');
  534. _deleteFolderValidate(index);
  535. },
  536. backgroundColor: Colors.red,
  537. foregroundColor: Colors.white,
  538. icon: Icons.delete,
  539. label: '删除',
  540. ),
  541. SlidableAction(
  542. onPressed: (_) {
  543. print('重命名目录。。。。。。。。');
  544. _showFolderDialog(_trees[index]);
  545. },
  546. backgroundColor: Colors.blue,
  547. foregroundColor: Colors.white,
  548. icon: Icons.edit,
  549. label: '重命名',
  550. )
  551. ];
  552. }
  553. }
  554. ///
  555. /// 底部弹出菜单 选择 新建脑图 新建文件夹
  556. ///
  557. void _showAddMenu() {
  558. BottomSheetHelper.show(context, <Widget>[
  559. ListTile(
  560. onTap: () {
  561. print('新建脑图。。。。。。。。');
  562. Navigator.of(context).pop();
  563. _showNewMindMap();
  564. },
  565. leading: const Icon(Icons.add_box),
  566. title: const Text('新建脑图', style: O2UI.primaryTextStyle),
  567. ),
  568. ListTile(
  569. onTap: () {
  570. Navigator.of(context).pop();
  571. _showFolderDialog(null);
  572. },
  573. leading: const Icon(Icons.create_new_folder),
  574. title: const Text('新建目录', style: O2UI.primaryTextStyle),
  575. )
  576. ]);
  577. }
  578. void _showMindMapOperationMenu(MindMap data) {
  579. print('显示菜单。。。${data.name}');
  580. BottomSheetHelper.show(context, <Widget>[
  581. ListTile(
  582. onTap: () {
  583. Navigator.of(context).pop();
  584. _renameMindMap(data);
  585. },
  586. leading: const Icon(Icons.edit),
  587. title: const Text('重命名', style: O2UI.primaryTextStyle),
  588. ),
  589. ListTile(
  590. onTap: () {
  591. Navigator.of(context).pop();
  592. _deleteMindMap(data);
  593. },
  594. leading: const Icon(Icons.delete_forever),
  595. title: const Text('删除', style: O2UI.primaryTextStyle),
  596. )
  597. ]);
  598. }
  599. void _showErrorSnap(String message) {
  600. O2SnackBars.showSnackBar(_scaffoldKey, message);
  601. }
  602. ///
  603. /// 新建目录
  604. ///
  605. void _showFolderDialog(MindFolder? old) {
  606. String title;
  607. String parentId;
  608. String? id;
  609. if (old != null) {
  610. newFolderEditingController?.text = old.name ?? '';
  611. title = '重命名';
  612. parentId = old.parentId!;
  613. id = old.id!;
  614. } else {
  615. newFolderEditingController?.text = '';
  616. title = '在【$_folderName】下新建目录';
  617. parentId = _folderId;
  618. id = null;
  619. }
  620. O2Dialogs.showCustomDialog(
  621. context: context,
  622. title: title,
  623. content: TextField(
  624. controller: newFolderEditingController,
  625. autofocus: true,
  626. decoration:
  627. const InputDecoration(labelText: '名称', hintText: '请输入目录名称'),
  628. )).then((action) {
  629. if (action == O2DialogAction.positive) {
  630. _newOrEditFolder(parentId, id);
  631. }
  632. });
  633. }
  634. ///
  635. /// 新建脑图Dialog
  636. ///
  637. void _showNewMindMap() {
  638. newFolderEditingController?.text = '';
  639. O2Dialogs.showCustomDialog(
  640. context: context,
  641. title: '在【$_folderName】下新建脑图',
  642. content: TextField(
  643. controller: newFolderEditingController,
  644. autofocus: true,
  645. decoration:
  646. const InputDecoration(labelText: '脑图名称', hintText: '请输入脑图名称'),
  647. )).then((action) {
  648. if (action == O2DialogAction.positive) {
  649. _newMindMap();
  650. }
  651. });
  652. }
  653. }