import 'dart:async'; import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart'; import 'package:amap_location_flutter_plugin/amap_location_option.dart'; import 'package:flutter/material.dart'; import 'package:liftmanager/common/common.dart'; import 'package:liftmanager/internal/news/news_router.dart'; import 'package:liftmanager/internal/news/model/news_comm_entity.dart'; import 'package:liftmanager/internal/news/presenter/news_home_presenter.dart'; import 'package:liftmanager/internal/search/presenter/base_list_provider.dart'; import 'package:liftmanager/internal/work/model/banner_entity.dart'; import 'package:liftmanager/internal/work/work_router.dart'; import 'package:liftmanager/mvp/base_page_state.dart'; import 'package:liftmanager/net/api_service.dart'; import 'package:liftmanager/res/resources.dart'; import 'package:liftmanager/routers/fluro_navigator.dart'; import 'package:liftmanager/utils/theme_utils.dart'; import 'package:liftmanager/utils/toast.dart'; import 'package:liftmanager/widgets/app_city_search_bar.dart'; import 'package:liftmanager/widgets/load_image.dart'; import 'package:liftmanager/widgets/my_refresh_list.dart'; import 'package:liftmanager/widgets/state_layout.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart' as p; import 'package:flustars/flustars.dart' as FlutterStars; class NewsPage extends StatefulWidget { @override NewsPageState createState() => NewsPageState(); } const timeout = const Duration(seconds: 5); class NewsPageState extends BasePageState with TickerProviderStateMixin, AutomaticKeepAliveClientMixin{ Map _locationResult; StreamSubscription> _locationListener; AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin(); BaseListProvider provider = BaseListProvider(); TabController _tabController; PageController _pageController = PageController(); int _index = 0; Timer _timer; int _page = 1; List bannerList = []; List menuTitle = ["互动问答", "电梯保险", "知识学堂"]; List menuImage = ["icon_tdgl", "icon_tdmp", "icon_tdmp"]; List menuDesc = ["1548人发起最新求助", "最高赔付200万", "海量知识任你学"]; String cityName = ""; @override void initState() { print("initState"); _locationListener = _locationPlugin .onLocationChanged() .listen((Map result) { setState(() { _locationPlugin.stopLocation(); _locationResult = result; // address latitude longitude _locationResult.forEach((key, value) { if(key == 'city'){ cityName = '$value'; setState(() { }); } print(111); print('key:$key :'); print('value:$value :'); }); }); }); /// 默认为加载中状态,本页面场景默认为空 provider.setStateTypeNotNotify(StateType.loading); _tabController = TabController(length: 0, vsync: this); _timer = Timer.periodic(timeout, _handleTimeout); super.initState(); // cityName = SpUtil.getString("cityName"); _onRefresh(); getBanner(); getUserInfo(); getLocation(); } void _setLocationOption() { if (null != _locationPlugin) { AMapLocationOption locationOption = new AMapLocationOption(); ///是否单次定位 locationOption.onceLocation = true; ///是否需要返回逆地理信息 locationOption.needAddress = true; ///逆地理信息的语言类型 locationOption.geoLanguage = GeoLanguage.DEFAULT; ///设置Android端连续定位的定位间隔 locationOption.locationInterval = 20000; ///设置Android端的定位模式
///可选值:
///
  • [AMapLocationMode.Battery_Saving]
  • ///
  • [AMapLocationMode.Device_Sensors]
  • ///
  • [AMapLocationMode.Hight_Accuracy]
  • locationOption.locationMode = AMapLocationMode.Hight_Accuracy; ///设置iOS端的定位最小更新距离
    locationOption.distanceFilter = -1; ///设置iOS端期望的定位精度 /// 可选值:
    ///
  • [DesiredAccuracy.Best] 最高精度
  • ///
  • [DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度
  • ///
  • [DesiredAccuracy.NearestTenMeters] 10米
  • ///
  • [DesiredAccuracy.Kilometer] 1000米
  • ///
  • [DesiredAccuracy.ThreeKilometers] 3000米
  • locationOption.desiredAccuracy = DesiredAccuracy.NearestTenMeters; ///设置iOS端是否允许系统暂停定位 locationOption.pausesLocationUpdatesAutomatically = false; ///将定位参数设置给定位插件 _locationPlugin.setLocationOption(locationOption); } } ///获取定位权限 Future requestPermission() async { final permissions = await PermissionHandler() .requestPermissions([PermissionGroup.location]); if (permissions[PermissionGroup.location] == PermissionStatus.granted) { return true; } else { toasts('需要定位权限!'); return false; } } ///获取用户信息 void getUserInfo() { ApiService(context: context).userInfo( onSuccess: (data) { if (!mounted) { return; } if(data != null){ FlutterStars.SpUtil.putString(Constant.companyRole,data.roleCode); } }, onError: (code, msg) { }); } ///获取位置信息 getLocation() async { if (await requestPermission()) { if (null != _locationPlugin) { ///开始定位之前设置定位参数 _setLocationOption(); _locationPlugin.startLocation(); } } } void getBanner() { ApiService(context: context).getBanner( onSuccess: (data) { bannerList = data; if (bannerList.length > 0) { _pageController.jumpToPage(0); _tabController = TabController(length: bannerList.length, vsync: this); setState(() {}); } }, onError: (code, msg) { showToast(msg); }); } _handleTimeout(Timer timer) { _index++; _pageController.animateToPage( _index % (bannerList.length == 0 ? 1 : bannerList.length), duration: Duration(milliseconds: 16), curve: Curves.fastOutSlowIn, ); } void _onPageChanged(int index) { _index = index; _tabController.animateTo(index); } @override void dispose() { _tabController?.dispose(); _timer.cancel(); _pageController.dispose(); ///移除定位监听 if (null != _locationListener) { _locationListener.cancel(); } ///销毁定位 if (null != _locationPlugin) { _locationPlugin.destroy(); } super.dispose(); } @override Widget build(BuildContext context) { bool isDark = ThemeUtils.isDark(context); return p.ChangeNotifierProvider>( create: (_) => provider, child: Scaffold( appBar: AppCitySearchAppBar( city: "$cityName", ), body: Container( color: ThemeUtils.getBackgroundColor(context), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Offstage( offstage: bannerList.length == 0, child: bannerWidget(), ), // Container( //// color: Colors.white, //// child: _ToolsItem(menuTitle, menuImage, menuDesc, (index) { //// if (index == 0) { ////// NavigatorUtils.push(context, AccountRouter.certificatePage); //// } else if (index == 1) { ////// NavigatorUtils.push(context, TeamRouter.teamUserPage); //// } //// }), //// ), Gaps.vGap10, Container( height: 45, padding: EdgeInsets.only(left: 15, right: 15), alignment: Alignment.centerLeft, decoration: BoxDecoration( color: isDark?Colours.dark_bg_color:Colors.white, border: Border( bottom: BorderSide(width: 0.5, color: Colours.line), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( padding: EdgeInsets.only(left: 10), decoration: BoxDecoration( border: Border( left: BorderSide(width: 3, color: Colours.app_main), )), child: Text( "热门新闻", style: TextStyles.textBold15, ), ), GestureDetector( onTap: () { NavigatorUtils.push( context, NewsRouter.newsTopList); }, child: Text( "更多", style: TextStyle( fontSize: 13, color: Color(0xFF666666)), )), ], ), ), Expanded( flex: 1, child: p.Consumer>( builder: (_, provider, __) { return MyListView( itemCount: provider.list.length, stateType: provider.stateType, onRefresh: _onRefresh, loadMore: _loadMore, // itemExtent: 67.0, hasMore: provider.hasMore, itemBuilder: (_, index) { var item = provider.list[index]; return InkWell( onTap: () { NavigatorUtils.push(context, "${NewsRouter.newsDetail}?id=${item.id}"); }, child: Container( decoration: BoxDecoration( color: isDark?Colours.dark_bg_color:Colors.white, border: Border( bottom: BorderSide( width: 0.5, color: Colours.line)), ), padding: const EdgeInsets.all(15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "${item.title}", style: TextStyle(fontSize: 15,color: isDark?Colours.dark_text:Colours.text), // overflow: TextOverflow.ellipsis, ), Gaps.vGap12, Text( "${item.releaseUser}·阅读${item.lookNum}次·点赞${item.likeNum}", style: TextStyle( fontSize: 11, color: Colours.text_gray), ) ], ), ), ); }, ); })) ], ), ), )); } Widget bannerWidget() { return Container( height: 160, child: Stack( children: [ PageView( children: bannerList.map((item) { return GestureDetector( onTap: (){ if(item.url.length>0){ NavigatorUtils.push(context, "${WorkRouter.webview}?title="+Uri.encodeComponent("详情")+"&url="+Uri.encodeComponent(item.url)); } }, child: Image.network( item.image, fit: BoxFit.fill, //使照片占满整个屏幕 ), ); }).toList(), onPageChanged: _onPageChanged, controller: _pageController, ), Align( alignment: Alignment(0.0, 0.9), child: TabPageSelector( color: Colors.white, selectedColor: Colours.app_main, controller: _tabController, ), ), ], )); } Widget lineTxt(title, value) { return Container( padding: EdgeInsets.only(left: 12, top: 5, right: 12), child: Row( children: [ Text("${title}", style: TextStyle(fontSize: 13, color: Colours.dark_text_gray)), Expanded( flex: 1, child: Text( "${value}", textAlign: TextAlign.right, style: TextStyle(fontSize: 13, color: Colours.dark_text_gray), ), ) ], ), ); } Future _onRefresh() async { _page = 1; await presenter.newsList(context, _page, 1, "", cityName); } Future _loadMore() async { _page++; await presenter.newsList(context, _page, 1, "", cityName); } @override NewsHomePresenter createPresenter() { return NewsHomePresenter(); } @override bool get wantKeepAlive => true; } class _ToolsItem extends StatelessWidget { _ToolsItem(this.titles, this.imgs, this.desc, this.onTap, {Key key}) : super(key: key); List titles; List imgs; List desc; Function onTap; @override Widget build(BuildContext context) { return GridView.builder( shrinkWrap: true, padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0), physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 0.9, crossAxisSpacing: 2), itemCount: titles.length, itemBuilder: (_, index) { return InkWell( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ LoadAssetImage( "work/${imgs[index]}", width: 45.0, height: 45, ), Gaps.vGap10, Text( titles[index], style: TextStyles.textSize14, ), Gaps.vGap10, Text( desc[index], style: TextStyles.textGray10, ) ], ), onTap: () { onTap(index); }); }, ); } }