123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431 |
- import 'dart:async';
- import 'dart:convert';
- import 'package:flutter/cupertino.dart';
- import 'package:flutter/material.dart' hide NestedScrollView;
- import 'package:flutter/services.dart';
- import 'package:flutter_easyrefresh/easy_refresh.dart';
- import 'package:get_it/get_it.dart';
- import 'package:permission_handler/permission_handler.dart';
- import 'package:qrscanner/flutter_plugin_qr_scanner.dart';
- import 'package:provider/provider.dart';
- import 'package:qr_flutter/qr_flutter.dart';
- import 'package:sport/bean/post_user.dart';
- import 'package:sport/bean/user_friend.dart';
- import 'package:sport/bean/user_info.dart';
- // import 'package:sport/pages/social/qr_view.dart';
- import 'package:sport/pages/social/user_detail_page.dart';
- import 'package:sport/provider/lib/provider_widget.dart';
- import 'package:sport/provider/lib/simple_model.dart';
- import 'package:sport/provider/lib/view_state_lifecycle.dart';
- import 'package:sport/provider/user_model.dart';
- import 'package:sport/router/navigator_util.dart';
- import 'package:sport/services/api/inject_api.dart';
- import 'package:sport/services/api/resp.dart';
- import 'package:sport/services/api/rest_client.dart';
- import 'package:sport/utils/click.dart';
- import 'package:sport/utils/toast.dart';
- import 'package:sport/widgets/appbar.dart';
- import 'package:sport/widgets/dialog/request_dialog.dart';
- import 'package:sport/widgets/dialog/scan_add_new_friend_dialog.dart';
- import 'package:sport/widgets/error.dart';
- import 'package:sport/widgets/image.dart';
- import 'package:sport/widgets/loading.dart';
- import 'package:sport/widgets/misc.dart';
- class UserFriendAddPage extends StatefulWidget {
- @override
- State<StatefulWidget> createState() => _PageState();
- }
- class _PageState extends ViewStateLifecycle<UserFriendAddPage, SimpleModel> with InjectApi {
- late TextEditingController _controller;
- late FocusNode _focusNode;
- ValueNotifier<String> _searchValue = ValueNotifier<String>("");
- var userCode; // 用户自己的二维码
- UserInfo? _newFriendUserInfo; // 扫码出来的那个逼的userInfo(请求回来的)
- // int dialogType; // 弹窗类型
- String? newFriendCode; // 扫码出来的要加的那个逼的二维码
- List<UserFriend> allUserFriends = []; // 等待添加的好友队列
- bool isWaiting = false; // 上锁解决
- Timer? timerIsFriend; // 轮询是否是好友
- int currentIndex = 0; // 不要用栈的方法 用指针的方法...
- @override
- SimpleModel createModel() => SimpleModel((page) async {
- if (_searchValue.value == "") return [];
- return (await api.userSearch(kw: _searchValue.value, page: page)).pageResult.results ?? [];
- });
- // // 试试 写写 ViewModel
- // SimpleDataModel friendModel() => SimpleDataModel<NewFriend>((code) async {
- // return (await api.getNewFriend(code)).data;
- // });
- @override
- void initState() {
- super.initState();
- _focusNode = FocusNode();
- _controller = new TextEditingController(text: '');
- initFriendCode();
- pollGetFriendRequest();
- _showConfirmDialog();
- }
- @override
- void dispose() {
- super.dispose();
- _focusNode.dispose();
- _controller.dispose();
- timerIsFriend?.cancel();
- }
- // 初始化 好友码...
- initFriendCode() async {
- var code = await api.getNewFriendCode();
- setState(() {
- userCode = jsonEncode(code.data);
- });
- }
- void _showConfirmDialog() async {
- if (_newFriendUserInfo != null) {
- // _newFriendUserInfo = (await GetIt.I<RestClient>().getUserInfo("10")).data;
- await showDialog(
- context: context,
- barrierDismissible: false,
- builder: (context) =>
- ScanAddFriendCustomAlertDialog(
- userInfo: _newFriendUserInfo!,
- newFriendCode: newFriendCode,
- ));
- }
- }
- void pollGetFriendRequest() async {
- // 获取 userFriends
- timerIsFriend = Timer.periodic(Duration(seconds: 2), (timer) async {
- List<UserFriend> userFriends = (await api.getFriendRequest()).results;
- if (userFriends.length > 0) {
- if (allUserFriends.length <= 0) {
- allUserFriends.addAll(userFriends);
- } else {
- Iterable<int> allUserFriendsId = allUserFriends.map((e) => e.socialInfo!.id!);
- // 去重...
- for (UserFriend _userfriend in userFriends) {
- if (!allUserFriendsId.contains(_userfriend.socialInfo!.id!)) {
- allUserFriends.add(_userfriend);
- }
- }
- }
- }
- if (!isWaiting && allUserFriends.length > 0 && currentIndex < allUserFriends.length) {
- isWaiting = true; //正在等待的意思...
- UserFriend currentUserFriend = allUserFriends[currentIndex];
- if (currentUserFriend.socialInfo != null) {
- bool? flag = await showDialog(
- context: context,
- barrierDismissible: false,
- builder: (context) => ScanAddFriendCustomAlertDialog(
- userInfo: currentUserFriend.socialInfo!,
- isWaitAdd: true,
- ));
- if (flag != null) {
- isWaiting = false;
- currentIndex += 1;
- }
- }
- }
- });
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- backgroundColor: Colors.white,
- appBar: buildAppBar(
- context,
- title: "二维码名片",
- actions: <Widget>[
- TextButton(
- onPressed: () async {
- var p = await Permission.camera.request();
- if (!p.isGranted) {
- ToastUtil.show("没有相机的使用权限");
- return;
- }
- String code;
- // Platform messages may fail, so we use a try/catch PlatformException.
- try {
- code = await QrScanner.scan(
- title: "扫一扫",
- laserColor: Theme.of(context).accentColor,
- //default #ffff55ff
- playBeep: true,
- //default false
- promptMessage: "将二维码放入框内,即可自动扫描",
- errorMsg: "扫描错误",
- permissionDeniedText: "请在设置中打开定位权限后继续使用",
- messageConfirmText: "确定",
- messageCancelText: "取消",
- );
- } on PlatformException {
- code = 'Failed to get qr code.';
- }
- var data = json.decode(code);
- UserInfo? _userInfo = (await api.getUserInfo('${data['uid']}')).data;
- setState(() {
- _newFriendUserInfo = _userInfo;
- newFriendCode = data['code'];
- _showConfirmDialog();
- });
- // ScanConfig scanConfig = ScanConfig();
- // SDScan scan =
- // SDScan().setScanEventListener((dynamic friendData) async {
- // // 扫描之后就去这个逼的 主页 爱关注 不关注的...
- // var data = json.decode(friendData);
- //
- // UserInfo _userInfo =
- // (await api.getUserInfo('${data['uid']}')).data;
- //
- // setState(() {
- // _newFriendUserInfo = _userInfo;
- // newFriendCode = data['code'];
- // _showConfirmDialog();
- // });
- // });
- // scan.startScan(config: scanConfig);
- }, child: Row(children: [
- Image.asset("lib/assets/img/fiends_image_scanning.png" ,width: 22.0,
- height: 22.0,),
- Padding(
- padding: const EdgeInsets.only(left: 6.0),
- child: Text("扫一扫", style: Theme.of(context).textTheme.subtitle1,),
- ),
- ],),
- ),
- ],
- ),
- body: ProviderWidget<SimpleModel>(
- model: model,
- onModelReady: (model) => model.initData(),
- builder: (_, model, __) {
- return EasyRefresh.custom(
- firstRefresh: false,
- onRefresh: () => model.refresh(),
- onLoad: () => model.loadMore(),
- enableControlFinishRefresh: true,
- controller: model.refreshController,
- header: buildClassicalHeader(),
- footer: buildClassicalFooter(),
- slivers: <Widget>[
- // SliverPersistentHeader(
- // delegate: PersistentHeader(
- //// min: 50,
- //// max: 50,
- // child: Container(
- // color: Colors.white,
- // child: _searchWidget(context),
- // )),
- // pinned: true,
- // ),
- SliverToBoxAdapter(
- child: _searchWidget(context),
- ),
- if (model.isBusy)
- SliverToBoxAdapter(
- child: RequestLoadingWidget(),
- ),
- if (model.isEmpty || model.isError)
- _searchValue.value != ""
- ? SliverToBoxAdapter(
- child: RequestErrorWidget(
- null,
- msg: "暂无相关用户~",
- ),
- )
- : SliverToBoxAdapter(),
- if (model.isIdle)
- SliverList(
- delegate: SliverChildBuilderDelegate(
- (context, index) {
- return _buildItem(model.list[index]);
- },
- childCount: model.list.length,
- ),
- ),
- if (!model.isIdle && userCode != null && _searchValue.value == "")
- SliverFillRemaining(
- child: Container(
- // height: double.infinity,
- alignment: Alignment.center,
- child: Consumer<UserModel>(
- builder: (_, model, __) => Center(
- child: QrImage(
- data: userCode, version: QrVersions.auto, size: 150, gapless: true, embeddedImage: userAvatarProvider("${model.user.avatar}"),),),
- ),
- )),
- ],
- );
- }),
- );
- }
- Widget _buildItem(UserInfo user) {
- Widget child = Row(
- children: <Widget>[
- CircleAvatar(backgroundColor: Colors.black26,
- backgroundImage: userAvatarProvider(user.avatar),
- radius: 22,
- ),
- SizedBox(
- width: 8,
- ),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Text(
- "${user.name}",
- style: Theme.of(context).textTheme.headline3,
- ),
- SizedBox(
- height: 4,
- ),
- Text(
- "ID: ${user.id}",
- style: Theme.of(context).textTheme.bodyText2!,
- ),
- ],
- ),
- ),
- user.isFriend()
- ? Container(
- width: 64,
- height: 30,
- margin: EdgeInsets.only(left: 8.0),
- alignment: Alignment.center,
- child: Text(
- "已关注",
- strutStyle: fixedLine,
- style: Theme.of(context).textTheme.bodyText2!.copyWith(color: Theme.of(context).accentColor),
- ),
- )
- : GestureDetector(
- child: Container(
- width: 64,
- height: 30,
- margin: EdgeInsets.only(left: 8.0),
- alignment: Alignment.center,
- child: Text(
- "关注",
- strutStyle: fixedLine,
- style: Theme.of(context).textTheme.bodyText2!.copyWith(color: Theme.of(context).accentColor),
- ),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(20),
- border: Border.all(
- color: Theme.of(context).accentColor,
- width: .5,
- ),
- ),
- ),
- onTap: () async {
- if (user.isFriend()) return;
- await request(context, () async {
- var resp = await model.api.userFollow(uid: user.id!).catchError((onError) {});
- if (resp.code == 0) {
- ToastUtil.show("关注成功");
- setState(() {
- user.followStatus = "followed";
- });
- }
- });
- },
- )
- ],
- );
- return Column(
- children: <Widget>[
- Padding(
- padding: const EdgeInsets.all(12.0),
- child: InkWell(
- onTap: () async {
- List<UserFriend> friends = model.list.map((e) => UserFriend(uid: user.id, socialInfo: user, isFriends: user.isFriend() ? "1" : "0")).toList();
- await NavigatorUtil.goTransparentPage(
- context, (context,_,__) => UserDetailPage(PostUser(id: "${user.id}", name: user.name, avatar: user.avatar), userFriends: friends));
- user.followStatus = friends.firstWhere((element) => element.uid == user.id).isFriends == "1" ? "followed" : "none";
- setState(() {});
- },
- child: child),
- ),
- Divider(
- height: 1,
- )
- ],
- );
- }
- Widget _searchWidget(BuildContext context) {
- return Container(
- margin: EdgeInsets.fromLTRB(12.0, 11.0, 12.0, 6.0),
- height: 35,
- padding: EdgeInsets.fromLTRB(12.0, 0, 12.0, 0),
- decoration: BoxDecoration(
- color: Color(0xffF1F1F1),
- shape: BoxShape.rectangle,
- borderRadius: BorderRadius.all(Radius.circular(50)),
- ),
- child: Row(
- children: <Widget>[
- Image.asset("lib/assets/img/searchbar_icon_search.png"),
- SizedBox(
- width: 6,
- ),
- Expanded(
- child: CupertinoTextField(
- cursorColor: const Color(0xffFFC400),
- controller: _controller,
- maxLines: 1,
- focusNode: _focusNode,
- style: Theme.of(context).textTheme.subtitle1,
- placeholder: "输入帐号/用户昵称",
- placeholderStyle: Theme.of(context).textTheme.bodyText2,
- decoration: BoxDecoration( // 文本框装饰
- color: Colors.transparent, // 文本框颜色
- ),
- onChanged: debounceValueChanged((value) {
- _searchValue.value = value;
- model.initData();
- }),
- onSubmitted: (value) {
- _focusNode.unfocus();
- },
- ),
- ),
- Visibility(
- visible: _searchValue.value.isNotEmpty == true,
- child: GestureDetector(
- onTap: () {
- _searchValue.value = "";
- model.initData();
- _controller.clear();
- },
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
- ),
- )),
- ],
- ),
- );
- }
- }
|