Flutter 藉助SearchDelegate實現搜索頁面,實現搜索建議、搜索結果,解決IOS拼音問題

来源:https://www.cnblogs.com/sw-code/p/18257792
-Advertisement-
Play Games

使用Flutter自帶的SearchDelegate組件實現搜索界面,通過魔改實現如下效果:搜素建議、搜索結果,支持刷新和載入更多,解決IOS中文輸入拼音問題。 ...


搜索界面使用Flutter自帶的SearchDelegate組件實現,通過魔改實現如下效果:

  1. 搜素建議
  2. 搜索結果,支持刷新和載入更多
  3. IOS中文輸入拼音問題

界面預覽

拷貝源碼

將SearchDelegate的源碼拷貝一份,修改內容如下:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 修改此處為 showMySearch
Future<T?> showMySearch<T>({
  required BuildContext context,
  required MySearchDelegate<T> delegate,
  String? query = '',
  bool useRootNavigator = false,
}) {
  delegate.query = query ?? delegate.query;
  delegate._currentBody = _SearchBody.suggestions;
  return Navigator.of(context, rootNavigator: useRootNavigator)
      .push(_SearchPageRoute<T>(
    delegate: delegate,
  ));
}

/// https://juejin.cn/post/7090374603951833118
abstract class MySearchDelegate<T> {
  MySearchDelegate({
    this.searchFieldLabel,
    this.searchFieldStyle,
    this.searchFieldDecorationTheme,
    this.keyboardType,
    this.textInputAction = TextInputAction.search,
  }) : assert(searchFieldStyle == null || searchFieldDecorationTheme == null);

  Widget buildSuggestions(BuildContext context);

  Widget buildResults(BuildContext context);

  Widget? buildLeading(BuildContext context);

  bool? automaticallyImplyLeading;

  double? leadingWidth;

  List<Widget>? buildActions(BuildContext context);

  PreferredSizeWidget? buildBottom(BuildContext context) => null;

  Widget? buildFlexibleSpace(BuildContext context) => null;

  ThemeData appBarTheme(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final ColorScheme colorScheme = theme.colorScheme;
    return theme.copyWith(
      appBarTheme: AppBarTheme(
        systemOverlayStyle: colorScheme.brightness == Brightness.dark
            ? SystemUiOverlayStyle.light
            : SystemUiOverlayStyle.dark,
        backgroundColor: colorScheme.brightness == Brightness.dark
            ? Colors.grey[900]
            : Colors.white,
        iconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
        titleTextStyle: theme.textTheme.titleLarge,
        toolbarTextStyle: theme.textTheme.bodyMedium,
      ),
      inputDecorationTheme: searchFieldDecorationTheme ??
          InputDecorationTheme(
            hintStyle: searchFieldStyle ?? theme.inputDecorationTheme.hintStyle,
            border: InputBorder.none,
          ),
    );
  }

  String get query => _queryTextController.completeText;

  set query(String value) {
    _queryTextController.completeText = value; // 更新實際搜索內容
    _queryTextController.text = value; // 更新輸入框內容
    if (_queryTextController.text.isNotEmpty) {
      _queryTextController.selection = TextSelection.fromPosition(
          TextPosition(offset: _queryTextController.text.length));
    }
  }

  void showResults(BuildContext context) {
    _focusNode?.unfocus();
    _currentBody = _SearchBody.results;
  }

  void showSuggestions(BuildContext context) {
    assert(_focusNode != null,
        '_focusNode must be set by route before showSuggestions is called.');
    _focusNode!.requestFocus();
    _currentBody = _SearchBody.suggestions;
  }

  void close(BuildContext context, T result) {
    _currentBody = null;
    _focusNode?.unfocus();
    Navigator.of(context)
      ..popUntil((Route<dynamic> route) => route == _route)
      ..pop(result);
  }

  final String? searchFieldLabel;

  final TextStyle? searchFieldStyle;

  final InputDecorationTheme? searchFieldDecorationTheme;

  final TextInputType? keyboardType;

  final TextInputAction textInputAction;

  Animation<double> get transitionAnimation => _proxyAnimation;

  FocusNode? _focusNode;

  final ChinaTextEditController _queryTextController = ChinaTextEditController();

  final ProxyAnimation _proxyAnimation =
      ProxyAnimation(kAlwaysDismissedAnimation);

  final ValueNotifier<_SearchBody?> _currentBodyNotifier =
      ValueNotifier<_SearchBody?>(null);

  _SearchBody? get _currentBody => _currentBodyNotifier.value;
  set _currentBody(_SearchBody? value) {
    _currentBodyNotifier.value = value;
  }

  _SearchPageRoute<T>? _route;

  /// Releases the resources.
  @mustCallSuper
  void dispose() {
    _currentBodyNotifier.dispose();
    _focusNode?.dispose();
    _queryTextController.dispose();
    _proxyAnimation.parent = null;
  }
}

/// search page.
enum _SearchBody {
  suggestions,

  results,
}

class _SearchPageRoute<T> extends PageRoute<T> {
  _SearchPageRoute({
    required this.delegate,
  }) {
    assert(
      delegate._route == null,
      'The ${delegate.runtimeType} instance is currently used by another active '
      'search. Please close that search by calling close() on the MySearchDelegate '
      'before opening another search with the same delegate instance.',
    );
    delegate._route = this;
  }

  final MySearchDelegate<T> delegate;

  @override
  Color? get barrierColor => null;

  @override
  String? get barrierLabel => null;

  @override
  Duration get transitionDuration => const Duration(milliseconds: 300);

  @override
  bool get maintainState => false;

  @override
  Widget buildTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
    return FadeTransition(
      opacity: animation,
      child: child,
    );
  }

  @override
  Animation<double> createAnimation() {
    final Animation<double> animation = super.createAnimation();
    delegate._proxyAnimation.parent = animation;
    return animation;
  }

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return _SearchPage<T>(
      delegate: delegate,
      animation: animation,
    );
  }

  @override
  void didComplete(T? result) {
    super.didComplete(result);
    assert(delegate._route == this);
    delegate._route = null;
    delegate._currentBody = null;
  }
}

class _SearchPage<T> extends StatefulWidget {
  const _SearchPage({
    required this.delegate,
    required this.animation,
  });

  final MySearchDelegate<T> delegate;
  final Animation<double> animation;

  @override
  State<StatefulWidget> createState() => _SearchPageState<T>();
}

class _SearchPageState<T> extends State<_SearchPage<T>> {
  // This node is owned, but not hosted by, the search page. Hosting is done by
  // the text field.
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    widget.delegate._queryTextController.addListener(_onQueryChanged);
    widget.animation.addStatusListener(_onAnimationStatusChanged);
    widget.delegate._currentBodyNotifier.addListener(_onSearchBodyChanged);
    focusNode.addListener(_onFocusChanged);
    widget.delegate._focusNode = focusNode;
  }

  @override
  void dispose() {
    super.dispose();
    widget.delegate._queryTextController.removeListener(_onQueryChanged);
    widget.animation.removeStatusListener(_onAnimationStatusChanged);
    widget.delegate._currentBodyNotifier.removeListener(_onSearchBodyChanged);
    widget.delegate._focusNode = null;
    focusNode.dispose();
  }

  void _onAnimationStatusChanged(AnimationStatus status) {
    if (status != AnimationStatus.completed) {
      return;
    }
    widget.animation.removeStatusListener(_onAnimationStatusChanged);
    if (widget.delegate._currentBody == _SearchBody.suggestions) {
      focusNode.requestFocus();
    }
  }

  @override
  void didUpdateWidget(_SearchPage<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.delegate != oldWidget.delegate) {
      oldWidget.delegate._queryTextController.removeListener(_onQueryChanged);
      widget.delegate._queryTextController.addListener(_onQueryChanged);
      oldWidget.delegate._currentBodyNotifier
          .removeListener(_onSearchBodyChanged);
      widget.delegate._currentBodyNotifier.addListener(_onSearchBodyChanged);
      oldWidget.delegate._focusNode = null;
      widget.delegate._focusNode = focusNode;
    }
  }

  void _onFocusChanged() {
    if (focusNode.hasFocus &&
        widget.delegate._currentBody != _SearchBody.suggestions) {
      widget.delegate.showSuggestions(context);
    }
  }

  void _onQueryChanged() {
    setState(() {
      // rebuild ourselves because query changed.
    });
  }

  void _onSearchBodyChanged() {
    setState(() {
      // rebuild ourselves because search body changed.
    });
  }

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterialLocalizations(context));
    final ThemeData theme = widget.delegate.appBarTheme(context);
    final String searchFieldLabel = widget.delegate.searchFieldLabel ??
        MaterialLocalizations.of(context).searchFieldLabel;
    Widget? body;
    switch (widget.delegate._currentBody) {
      case _SearchBody.suggestions:
        body = KeyedSubtree(
          key: const ValueKey<_SearchBody>(_SearchBody.suggestions),
          child: widget.delegate.buildSuggestions(context),
        );
      case _SearchBody.results:
        body = KeyedSubtree(
          key: const ValueKey<_SearchBody>(_SearchBody.results),
          child: widget.delegate.buildResults(context),
        );
      case null:
        break;
    }

    late final String routeName;
    switch (theme.platform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        routeName = '';
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        routeName = searchFieldLabel;
    }

    return Semantics(
      explicitChildNodes: true,
      scopesRoute: true,
      namesRoute: true,
      label: routeName,
      child: Theme(
        data: theme,
        child: Scaffold(
          appBar: AppBar(
            leadingWidth: widget.delegate.leadingWidth,
            automaticallyImplyLeading:
                widget.delegate.automaticallyImplyLeading ?? true,
            leading: widget.delegate.buildLeading(context),
            title: TextField(
              controller: widget.delegate._queryTextController,
              focusNode: focusNode,
              style: widget.delegate.searchFieldStyle ??
                  theme.textTheme.titleLarge,
              textInputAction: widget.delegate.textInputAction,
              keyboardType: widget.delegate.keyboardType,
              onSubmitted: (String _) => widget.delegate.showResults(context),
              decoration: InputDecoration(hintText: searchFieldLabel),
            ),
            flexibleSpace: widget.delegate.buildFlexibleSpace(context),
            actions: widget.delegate.buildActions(context),
            bottom: widget.delegate.buildBottom(context),
          ),
          body: AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            child: body,
          ),
        ),
      ),
    );
  }
}

class ChinaTextEditController extends TextEditingController {
  ///拼音輸入完成後的文字
  var completeText = '';

  @override
  TextSpan buildTextSpan(
      {required BuildContext context,
      TextStyle? style,
      required bool withComposing}) {
    ///拼音輸入完成
    if (!value.composing.isValid || !withComposing) {
      if (completeText != value.text) {
        completeText = value.text;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          notifyListeners();
        });
      }
      return TextSpan(style: style, text: text);
    }

    ///返回輸入樣式,可自定義樣式
    final TextStyle composingStyle = style?.merge(
      const TextStyle(decoration: TextDecoration.underline),
    ) ?? const TextStyle(decoration: TextDecoration.underline);
    return TextSpan(style: style, children: <TextSpan>[
      TextSpan(text: value.composing.textBefore(value.text)),
      TextSpan(
        style: composingStyle,
        text: value.composing.isValid && !value.composing.isCollapsed
            ? value.composing.textInside(value.text)
            : "",
      ),
      TextSpan(text: value.composing.textAfter(value.text)),
    ]);
  }
}

實現搜索

創建SearchPage繼承MySearchDelegate,修改樣式,實現頁面。需要重寫下麵5個方法

  • appBarTheme:修改搜索樣式
  • buildActions:搜索框右側的方法
  • buildLeading:搜索框左側的返回按鈕
  • buildResults:搜索結果
  • buildSuggestions:搜索建議
import 'package:e_book_clone/pages/search/MySearchDelegate.dart';
import 'package:flutter/src/material/theme_data.dart';
import 'package:flutter/src/widgets/framework.dart';

class Demo extends MySearchDelegate {

  @override
  ThemeData appBarTheme(BuildContext context) {
    // TODO: implement appBarTheme
    return super.appBarTheme(context);
  }
  
  @override
  List<Widget>? buildActions(BuildContext context) {
    // TODO: implement buildActions
    throw UnimplementedError();
  }

  @override
  Widget? buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    throw UnimplementedError();
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    throw UnimplementedError();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    throw UnimplementedError();
  }
}

修改樣式

@override
ThemeData appBarTheme(BuildContext context) {
  final ThemeData theme = Theme.of(context);
  final ColorScheme colorScheme = theme.colorScheme;
  return theme.copyWith( // 使用copyWith,適配全局主題
    appBarTheme: AppBarTheme( // AppBar樣式修改
      systemOverlayStyle: colorScheme.brightness == Brightness.dark
          ? SystemUiOverlayStyle.light
          : SystemUiOverlayStyle.dark,
      surfaceTintColor: Theme.of(context).colorScheme.surface,
      titleSpacing: 0, // textfield前面的間距
      elevation: 0, // 陰影
    ),
    inputDecorationTheme: InputDecorationTheme(
      isCollapsed: true,
      hintStyle: TextStyle( // 提示文字顏色
          color: Theme.of(ToastUtils.context).colorScheme.inversePrimary),
      filled: true,  // 填充顏色
      contentPadding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 15.w),
      fillColor: Theme.of(context).colorScheme.secondary, // 填充顏色,需要配合 filled
      enabledBorder: OutlineInputBorder( // testified 邊框
        borderRadius: BorderRadius.circular(12.r),
        borderSide: BorderSide(
          color: Theme.of(context).colorScheme.surface,
        ),
      ),
      focusedBorder: OutlineInputBorder( // testified 邊框
        borderRadius: BorderRadius.circular(12.r),
        borderSide: BorderSide(
          color: Theme.of(context).colorScheme.surface,
        ),
      ),
    ),
  );
}

@override
TextStyle? get searchFieldStyle => TextStyle(fontSize: 14.sp); // 字體大小設置,主要是覆蓋預設樣式

按鈕功能

左側返回按鈕,右側就放了一個搜索文本,點擊之後顯示搜索結果

@override
Widget? buildLeading(BuildContext context) {
  return IconButton(
    onPressed: () {
      close(context, null);
    },
    icon: Icon(
      color: Theme.of(context).colorScheme.onSurface,
      Icons.arrow_back_ios_new,
      size: 20.r,
    ),
  );
}

@override
List<Widget>? buildActions(BuildContext context) {
  return [
    Padding(
      padding: EdgeInsets.only(right: 15.w, left: 15.w),
      child: GestureDetector(
        onTap: () {
          showResults(context);
        },
        child: Text(
          '搜索',
          style: TextStyle(
              color: Theme.of(context).colorScheme.primary, fontSize: 15.sp),
        ),
      ),
    )
  ];
}

搜索建議

當 TextField 輸入變化時,就會調用buildSuggestions方法,刷新佈局,因此考慮使用FlutterBuilder管理頁面和數據。

final SearchViewModel _viewModel = SearchViewModel();

@override
Widget buildSuggestions(BuildContext context) {
  if (query.isEmpty) {
    // 這裡可以展示熱門搜索等,有搜索建議時,熱門搜索會被替換成搜索建議
    return const SizedBox();
  }
  return FutureBuilder(
    future: _viewModel.getSuggest(query),
    builder: (BuildContext context, AsyncSnapshot<List<Suggest>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        // 數據載入中
        return const Center(child: CircularProgressIndicator());
      } else if (snapshot.hasError) {
        // 數據載入錯誤
        return Center(child: Text('Error: ${snapshot.error}'));
      } else if (snapshot.hasData) {
        // 數據載入成功,展示結果
        final List<Suggest> searchResults = snapshot.data ?? [];
        return ListView.builder(
            padding: EdgeInsets.all(15.r),
            itemCount: searchResults.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () {
                  // 更新輸入框
                  query = searchResults[index].text ?? query;
                  showResults(context);
                },
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 10.h),
                  decoration: BoxDecoration(
                    border: BorderDirectional(
                      bottom: BorderSide(
                        width: 0.6,
                        color: Theme.of(context).colorScheme.surfaceContainer,
                      ),
                    ),
                  ),
                  child: Text('${searchResults[index].text}'),
                ),
              );
            });
      } else {
        // 數據為空
        return const Center(child: Text('No results found'));
      }
    },
  );
}

實體類代碼如下:

class Suggest {
  Suggest({
    this.id,
    this.url,
    this.text,
    this.isHot,
    this.hotLevel,
  });

  Suggest.fromJson(dynamic json) {
    id = json['id'];
    url = json['url'];
    text = json['text'];
    isHot = json['is_hot'];
    hotLevel = json['hot_level'];
  }

  String? id;
  String? url;
  String? text;
  bool? isHot;
  int? hotLevel;
}

ViewModel代碼如下:

class SearchViewModel {
  Future<List<Suggest>> getSuggest(String keyword) async {
    if (keyword.isEmpty) {
      return [];
    }
    return await JsonApi.instance().fetchSuggestV3(keyword);
  }
}

搜索結果

我們需要搜索結果頁面支持載入更多,這裡用到了 SmartRefrsh 組件

flutter pub add pull_to_refresh

buildResults方法是通過調用showResults(context);方法刷新頁面,因此為了方便數據動態變化,新建search_result_page.dart頁面

import 'package:e_book_clone/components/book_tile/book_tile_vertical/my_book_tile_vertical_item.dart';
import 'package:e_book_clone/components/book_tile/book_tile_vertical/my_book_tile_vertical_item_skeleton.dart';
import 'package:e_book_clone/components/my_smart_refresh.dart';
import 'package:e_book_clone/models/book.dart';
import 'package:e_book_clone/models/types.dart';
import 'package:e_book_clone/pages/search/search_vm.dart';
import 'package:e_book_clone/utils/navigator_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchResultPage extends StatefulWidget {
  final String query; // 請求參數
  const SearchResultPage({super.key, required this.query});

  @override
  State<SearchResultPage> createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  final RefreshController _refreshController = RefreshController();
  final SearchViewModel _viewModel = SearchViewModel();
  void loadOrRefresh(bool loadMore) {
    _viewModel.getResults(widget.query, loadMore).then((_) {
      if (loadMore) {
        _refreshController.loadComplete();
      } else {
        _refreshController.refreshCompleted();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    loadOrRefresh(false);
  }

  @override
  void dispose() {
    _viewModel.isDispose = true;
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<SearchViewModel>.value(
      value:  _viewModel,
      builder: (context, child) {
        return Consumer<SearchViewModel>(
          builder: (context, vm, child) {
            List<Book>? searchResult = vm.searchResult;
            // 下拉刷新和上拉載入組件
            return MySmartRefresh(
              enablePullDown: false,
              onLoading: () {
                loadOrRefresh(true);
              },
              controller: _refreshController,
              child: ListView.builder(
                padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
                itemCount: searchResult?.length ?? 10,
                itemBuilder: (context, index) {
                  if (searchResult == null) {
                    // 骨架屏 
                    return MyBookTileVerticalItemSkeleton(
                        width: 80.w, height: 120.h);
                  }
                  // 結果渲染組件
                  return MyBookTileVerticalItem(
                    book: searchResult[index],
                    width: 80.w,
                    height: 120.h,
                    onTap: (id) {
                      NavigatorUtils.nav2Detail(
                          context, DetailPageType.ebook, searchResult[index]);
                    },
                  );
                },
              ),
            );
          },
        );
      },
    );
  }
}

MySmartRefresh組件代碼如下,主要是對SmartRefresher做了進一步的封裝

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MySmartRefresh extends StatelessWidget {
  // 啟用下拉
  final bool? enablePullDown;

  // 啟用上拉
  final bool? enablePullUp;

  // 頭佈局
  final Widget? header;

  // 尾佈局
  final Widget? footer;

  // 刷新事件
  final VoidCallback? onRefresh;

  // 載入事件
  final VoidCallback? onLoading;

  // 刷新組件控制器
  final RefreshController controller;

  final ScrollController? scrollController;

  // 被刷新的子組件
  final Widget child;

  const MySmartRefresh({
    super.key,
    this.enablePullDown,
    this.enablePullUp,
    this.header,
    this.footer,
    this.onLoading,
    this.onRefresh,
    required this.controller,
    required this.child,
    this.scrollController,
  });

  @override
  Widget build(BuildContext context) {
    return _refreshView();
  }

  Widget _refreshView() {
    return SmartRefresher(
      scrollController: scrollController,
      controller: controller,
      enablePullDown: enablePullDown ?? true,
      enablePullUp: enablePullUp ?? true,
      header: header ?? const ClassicHeader(),
      footer: footer ?? const ClassicFooter(),
      onRefresh: onRefresh,
      onLoading: onLoading,
      child: child,
    );
  }
}

SearchViewModel 代碼如下:

import 'package:e_book_clone/http/spider/json_api.dart';
import 'package:e_book_clone/models/book.dart';
import 'package:e_book_clone/models/query_param.dart';
import 'package:e_book_clone/models/suggest.dart';
import 'package:flutter/material.dart';

class SearchViewModel extends ChangeNotifier {
  int _currPage = 2;
  bool isDispose = false;
  List<Book>? _searchResult;

  List<Book>? get searchResult => _searchResult;

  Future<List<Suggest>> getSuggest(String keyword) async {
    if (keyword.isEmpty) {
      return [];
    }
    return await JsonApi.instance().fetchSuggestV3(keyword);
  }

  Future getResults(String keyword, bool loadMore, {VoidCallback? callback}) async {
    if (loadMore) {
      _currPage++;
    } else {
      _currPage = 1;
      _searchResult?.clear();
    }

    // 請求參數
    SearchParam param = SearchParam(
      page: _currPage,
      rootKind: null,
      q: keyword,
      sort: "defalut",
      query: SearchParam.ebookSearch,
    );
    // 請求結果
    List<Book> res = await JsonApi.instance().fetchEbookSearch(param);
	
    // 載入更多,使用addAll
    if (_searchResult == null) {
      _searchResult = res;
    } else {
      _searchResult!.addAll(res);
    }

    if (res.isEmpty && _currPage > 0) {
      _currPage--;
    }
    // 防止Provider被銷毀,數據延遲請求去通知報錯
    if (isDispose) return;
    notifyListeners();
  }
}

buildResults方法如下:

@override
Widget buildResults(BuildContext context) {
  if (query.isEmpty) {
    return const SizedBox();
  }
  return SearchResultPage(query: query);
}

顯示搜索界面

註意調用的是我們自己拷貝修改的MySearchDelegate中的方法

onTap: () {
  showMySearch(context: context, delegate: SearchPage());
},

更多內容見

本文來自博客園,作者:sw-code,轉載請註明原文鏈接:https://www.cnblogs.com/sw-code/p/18257792


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Elasticsearch聚合查詢是一種強大的工具,允許我們對索引中的數據進行複雜的統計分析和計算。本文將詳細解釋一個聚合查詢示例,該查詢用於統計滿足特定條件的文檔數量,並計算其占總文檔數量的百分比。這裡回會分享如何統計某個欄位的空值率,然後擴展介紹ES的一些基礎知識。 ...
  • 在大數據時代,數據具有多源異構的特性,且價值各異,企業需依據數據的重要性、價值指數等予以區分,以利採取不同的數據保護舉措,避免數據泄露。故而,數據分類分級管理屬於數據安全保護中極為重要的環節之一。 2021 年 12 月 31 日,全國信息安全標準化技術委員會秘書處頒佈了《網路安全標準實踐指南——網 ...
  • 開發業務系統時,是繞不開RDBMS(關係型資料庫)的。雖然現在誕生了各種NoSQL的資料庫,RDBMS在業務系統中的嚴謹和優勢依然無法取代。 近幾年大大小小的項目中,常用的三種RDBMS(SQLite,MySQL,Postgres)都有多次接觸過,一些使用心得記錄如下,供大家參考。 1. SQLit ...
  • Android無障礙服務可以操作元素,手勢模擬,實現基本的控制。opencv可以進行圖像識別。兩者結合在一起即可實現支付寶能量自動收集。opencv用於識別能量,無障礙服務用於模擬手勢,即點擊能量。 當然這兩者結合不單單隻能實現這些,還能做很多自動化的程式,如芭芭農場自動施肥、螞蟻莊園等等的自動化, ...
  • 前提: Xcode 16.0 beta 設置 Scheme設置中勾選Malloc Scribble、Malloc Stack Logging。 這麼做是為了在Memory Graph、Profile中追溯數據在哪句代碼生成。 此設置會導致App硬碟占用異常增多,調試完畢之後需要把選項關閉。 Allo ...
  • Kotlin中變數類型由值決定,如Int、Double、Char、Boolean、String。通常可省略類型聲明,但有時需指定。數字類型分整數(Byte, Short, Int, Long)和浮點(Float, Double),預設整數為Int,浮點為Double。布爾值是true或false,C... ...
  • ASeeker 是一個 Android 源碼應用系統服務介面掃描工具。是我們在做虛擬化分身產品『 空殼 』過程中的內部開發工具,目的是為了提升 Android 系統各版本適配效率。 ...
  • 11.2警告郵件內容 Hello XXX, We're writing to inform you that your company isn't in compliance with the Apple Developer Program License Agreement (DPLA). Sec ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...