123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561 |
- import 'package:flutter/material.dart';
- import 'package:flutter_easyrefresh/easy_refresh.dart';
- import 'package:provider/provider.dart';
- import 'package:sport/bean/post.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/post_widget.dart';
- import 'package:sport/pages/social/user_detail_page.dart';
- import 'package:sport/provider/lib/provider_widget.dart' as p;
- import 'package:sport/provider/lib/provider_widget_selector.dart';
- import 'package:sport/provider/lib/simple_model.dart';
- import 'package:sport/provider/search_model.dart';
- import 'package:sport/provider/social_detail_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/userid.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/error.dart';
- import 'package:sport/widgets/image.dart';
- import 'package:sport/widgets/loading.dart';
- import 'package:sport/widgets/misc.dart';
- import 'package:sport/widgets/space.dart';
- class SearchPage extends StatefulWidget {
- @override
- State<StatefulWidget> createState() => _PageState();
- }
- class _PageState extends State<SearchPage> with UserId, InjectApi {
- late TextEditingController _controller;
- late FocusNode _focusNode;
- late SearchModel _model;
- late SocialDetailModel _searchModel;
- final double tabHeader = 50;
- late SimpleModel simpleModel;
- @override
- void initState() {
- super.initState();
- _focusNode = FocusNode();
- _controller = new TextEditingController(text: '');
- _model = SearchModel()
- ..getHistory()
- ..getHot();
- _searchModel = SocialDetailModel(
- 100,
- );
- simpleModel = new SimpleModel((page) async {
- var list = (await api.userSearch(kw: _controller.text, page: page)).pageResult.results;
- return list ?? [];
- });
- }
- @override
- void dispose() {
- super.dispose();
- _focusNode.dispose();
- _controller.dispose();
- _searchModel.dispose();
- }
- _submitValue(String value) {
- // _controller.text = value;
- _model.queryValue(value);
- _searchModel.setKeyword(value);
- simpleModel.loadData();
- // _focusNode?.unfocus();
- }
- @override
- Widget build(BuildContext context) {
- return ProviderWidget<SearchModel, SearchBody>(
- model: _model,
- selector: (_, model) {
- return model.currentBody;
- },
- shouldRebuild: (_, __) => true,
- builder: (BuildContext context, _body, Widget? child) {
- Widget body;
- switch (_body) {
- case SearchBody.defaultBody:
- body = _buildDefaultWidget();
- break;
- case SearchBody.suggestions:
- // body = buildSuggestions(context);
- // break;
- case SearchBody.results:
- body = buildResults(context);
- break;
- }
- return Scaffold(
- backgroundColor: Colors.white,
- appBar: AppBar(
- titleSpacing: 0,
- centerTitle: false,
- automaticallyImplyLeading: false,
- title: Container(
- margin: EdgeInsets.fromLTRB(12.0, 0, 6.0, 0),
- height: 35,
- decoration: BoxDecoration(
- color: Color(0xffF1F1F1),
- shape: BoxShape.rectangle,
- borderRadius: BorderRadius.all(Radius.circular(50)),
- ),
- child: Row(
- children: <Widget>[
- Space(
- width: 12,
- ),
- Image.asset("lib/assets/img/searchbar_icon_search.png"),
- Space(
- width: 6,
- ),
- Expanded(
- child: Selector<SearchModel, String>(
- selector: (_, model) => model.searchValue,
- builder: (context, _value, child) => Container(
- constraints: BoxConstraints(maxHeight: 30),
- child: TextField(
- controller: _controller,
- maxLines: 1,
- focusNode: _focusNode,
- decoration: InputDecoration(
- hintText: '请输入搜索内容',
- contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
- border: OutlineInputBorder(borderSide: BorderSide.none),
- hintStyle: TextStyle(color: Color(0xff999999))),
- onChanged: debounceValueChanged((value) {
- if (value != "") {
- _submitValue(value);
- }
- _model.queryValue(value);
- Provider.of<SearchModel>(context, listen: false).updateSearchValue(value);
- }),
- onSubmitted: (value) {
- _submitValue(value);
- // _searchModel.setKeyword(value);
- // Provider.of<SearchModel>(context, listen: false).queryValue(value);
- },
- ),
- ),
- )),
- Visibility(
- visible: context.select<SearchModel, String>((value) => value.searchValue).isNotEmpty,
- child: GestureDetector(
- onTap: () {
- Provider.of<SearchModel>(context, listen: false).updateSearchValue("");
- _controller.clear();
- },
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
- ),
- ))
- ],
- ),
- ),
- actions: <Widget>[
- buildActionButton("取消", () {
- Navigator.of(context).pop();
- }, textColor: Color(0xff333333)),
- ],
- ),
- body: AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- child: body,
- ),
- );
- },
- );
- }
- Widget _buildDefaultWidget() {
- return CustomScrollView(
- slivers: <Widget>[
- SliverPadding(
- padding: EdgeInsets.all(12.0),
- sliver: SliverToBoxAdapter(
- child: Selector<SearchModel, List>(
- selector: (_, model) => model.hot,
- builder: (context, _value, child) {
- if (_value.isNotEmpty) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Text("热门帖子", style: Theme.of(context).textTheme.headline3!.copyWith(fontSize: 18)),
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 6.0),
- child: Wrap(
- spacing: 12,
- children: _value.take(10).map((e) {
- return GestureDetector(
- onTap: () {
- _controller.text = e;
- _submitValue(e);
- // _model.queryValue(e);
- },
- child: Chip(
- labelPadding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 0),
- label: Text("$e"),
- labelStyle: TextStyle(color: Color(0xff666666)),
- backgroundColor: Colors.white,
- shape: StadiumBorder(
- side: BorderSide(color: Color(0xffDCDCDC), width: 0.5),
- ),
- ));
- }).toList()),
- ),
- ],
- );
- }
- return Container();
- },
- ),
- ),
- ),
- SliverPadding(
- padding: EdgeInsets.all(12.0),
- sliver: SliverToBoxAdapter(
- child: Selector<SearchModel, List>(
- selector: (_, model) => model.history,
- builder: (context, _value, child) {
- if (_value != null && _value.isNotEmpty) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("历史搜索", style: Theme.of(context).textTheme.headline3!.copyWith(fontSize: 18)),
- InkWell(
- onTap: () {
- _model.clearHistory();
- },
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Image.asset("lib/assets/img/list_icon_del.png"),
- ),
- )
- ],
- ),
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 6.0),
- child: Wrap(
- alignment: WrapAlignment.spaceBetween,
- spacing: 12,
- children: _value.map((e) {
- return GestureDetector(
- onTap: () {
- _controller.text = e;
- _submitValue(e);
- // _model.queryValue(e);
- },
- child: Chip(
- labelPadding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 0),
- label: Text("$e"),
- labelStyle: TextStyle(color: Color(0xff666666)),
- backgroundColor: Colors.white,
- shape: StadiumBorder(
- side: BorderSide(color: Color(0xffDCDCDC), width: 0.5),
- ),
- ));
- }).toList(),
- ),
- ),
- ],
- );
- }
- return Container();
- },
- ),
- ),
- )
- ],
- );
- }
- Widget buildSuggestions(BuildContext context) {
- return FutureBuilder(
- future: _model.api.getPostList(kw: _model.searchValue),
- builder: (context, AsyncSnapshot<RespPage<Post>> snapshot) => snapshot.connectionState == ConnectionState.done
- ? snapshot.data?.code == 0
- ? snapshot.data?.pageResult.results?.isEmpty == true
- ? Center(
- child: RequestErrorWidget(
- null,
- msg: "暂时找不到您想搜索的东西喔",
- ))
- : ListView.separated(
- itemBuilder: (context, index) {
- var item = snapshot.data!.pageResult.results![index];
- return ListTile(
- title: Text(
- item.content ?? "",
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- onTap: () {
- // query = '老孟 $index';
- String value = item.content ?? "";
- _submitValue(value);
- // NavigatorUtil.goSocialPostDetail(context, item);
- },
- trailing: arrowRight(),
- );
- },
- separatorBuilder: (context, index) {
- return Divider(
- height: 1,
- indent: 12,
- endIndent: 12,
- );
- },
- itemCount: snapshot.data!.pageResult.results!.length,
- )
- : Container()
- : Container(),
- );
- }
- Widget buildResults(BuildContext context) {
- return DefaultTabController(
- length: 2,
- child: Column(
- children: <Widget>[
- Container(
- color: Colors.white,
- height: tabHeader,
- padding: EdgeInsets.symmetric(vertical: 8.0),
- child: TabBar(
- isScrollable: true,
- indicatorPadding: EdgeInsets.symmetric(horizontal: 6),
- indicatorWeight: 3,
- tabs: <Widget>[
- Tab(text: "帖子"),
- Tab(text: "用户"),
- ],
- ),
- alignment: Alignment.centerLeft,
- ),
- Expanded(
- child: TabBarView(
- children: <Widget>[
- p.ProviderWidget<SocialDetailModel>(
- model: _searchModel,
- autoDispose: false, // 自动 dispose
- builder: (_, model, __) {
- return EasyRefresh.custom(
- controller: model.refreshController,
- enableControlFinishRefresh: true,
- enableControlFinishLoad: true,
- onLoad: model.isIdle ? () => model.loadMore() : null,
- header: buildClassicalHeader(),
- footer: buildClassicalFooter(),
- slivers: <Widget>[
- if (model.isBusy)
- SliverToBoxAdapter(
- child: RequestLoadingWidget(),
- ),
- if (model.isEmpty)
- SliverToBoxAdapter(
- child: RequestErrorWidget(
- null,
- msg: "暂时找不到您想搜索的东西喔",
- assets: RequestErrorWidget.ASSETS_NO_MOTION,
- ),
- ),
- SliverList(
- delegate: SliverChildBuilderDelegate(
- (context, index) {
- Post post = model.list[index];
- return PostWidget(
- post,
- _searchModel,
- selfId == post.userId,
- keyword: _controller.text,
- highlight: true,
- );
- },
- childCount: model.list.length,
- ),
- ),
- ],
- );
- },
- ),
- p.ProviderWidget<SimpleModel>(
- model: simpleModel,
- onModelReady: (model) => model.initData(),
- autoDispose: false,
- builder: (_, model, __) {
- return EasyRefresh.custom(
- // firstRefresh: true,
- controller: model.refreshController,
- enableControlFinishRefresh: true,
- enableControlFinishLoad: true,
- onLoad: model.isIdle ? () => model.initData() : null,
- header: buildClassicalHeader(),
- footer: buildClassicalFooter(),
- slivers: <Widget>[
- if (model.isBusy)
- SliverToBoxAdapter(
- child: RequestLoadingWidget(),
- ),
- if (model.isEmpty || model.isError)
- SliverToBoxAdapter(
- child: RequestErrorWidget(
- null,
- msg: _model.searchValue == "" ? "请输入搜索的关键字1" : "暂无相关用户~",
- ),
- ),
- if (model.isIdle)
- SliverList(
- delegate: SliverChildBuilderDelegate(
- (context, index) {
- return _buildItem(model.list[index]);
- },
- childCount: model.list.length,
- ),
- ),
- ],
- );
- },
- ),
- ],
- ),
- )
- ],
- ),
- );
- }
- 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 simpleModel.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 =
- simpleModel.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,
- )
- ],
- );
- }
- }
- class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
- final TabBar child;
- StickyTabBarDelegate({required this.child});
- @override
- Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
- return this.child;
- }
- @override
- double get maxExtent => this.child.preferredSize.height;
- @override
- double get minExtent => this.child.preferredSize.height;
- @override
- bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
- return true;
- }
- }
|