Flutter 從0搭建一個(gè)完整的項(xiàng)目(二、自定義加載頁面)

核心理念

化繁為簡,最終使用時(shí),簡單易用,擴(kuò)展性強(qiáng)即可。
1.頁面的加載過程
根據(jù)項(xiàng)目實(shí)際開發(fā),頁面加載過程基本上是確定的,主要為:加載頁面、錯(cuò)誤頁面、成功頁面、空頁面。
2.自定義加載控件,代碼比較簡單直接看就好
/// 1.加載狀態(tài):加載中 成功 錯(cuò)誤 空頁面
enum LoadingState { loading, success, error, empty }

/// 2.成功的構(gòu)建器
typedef ContentBuilder = Widget Function(BuildContext context);

/// 3.自定義加載控件
class LoadingLayout extends StatelessWidget {
  const LoadingLayout(
      {super.key,
      this.state = LoadingState.loading,// 默認(rèn)加載中
      this.retry,
      required this.contentBuilder});

  final LoadingState state;
  final VoidCallback? retry; // 錯(cuò)誤 空頁面 點(diǎn)擊回調(diào)
  final ContentBuilder contentBuilder; // 成功的頁面 子類實(shí)現(xiàn)

  @override
  Widget build(BuildContext context) {
    if (state == LoadingState.loading) { // 加載狀態(tài)
      return _loading();
    } else if (state == LoadingState.error) { // 錯(cuò)誤狀態(tài)
      return _emptyOrError("images/loading_ic_error.png", "頁面異常,點(diǎn)擊重試");
    } else if (state == LoadingState.empty) { // 空狀態(tài)
      return _emptyOrError("images/loading_ic_empty.png", "暫無數(shù)據(jù)");
    }
    // 成功狀態(tài)
    return contentBuilder(context);
  }

  /// 根據(jù)項(xiàng)目自己修復(fù)即可
  Widget _emptyOrError(String icon, String desc) {
    return GestureDetector(
      onTap: retry,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              icon,
              width: 80,
              height: 80,
            ),
            Text(
              desc,
              style: const TextStyle(fontSize: 16),
            ),
            const Text(
              "輕觸重試",
              style: TextStyle(fontSize: 14),
            )
          ],
        ),
      ),
    );
  }

  /// 加載中
  Widget _loading() {
    return Center(
      child: CircularProgressIndicator(
        color: Colors.orange.shade100,
      ),
    );
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容