簡體   English   中英

自定義腳手架 class 不繪制 AppBar

[英]Custom Scaffold class not draw the AppBar

我正在嘗試創建一個擴展原始 class 的自定義腳手架。 如果沒有通過一個新的 AppBar,則使用默認的 AppBar。

class CommonScaffold extends Scaffold {
  final AppBar? appBar;
  final Widget body;

  CommonScaffold({
    Key? key,
    this.appBar,
    required this.body,
  }) : super(
    key: key,
    body: body,
    appBar: appBar ??
        AppBar(
          title: const Text("Default Text"),
        ),
  );
}

如果我調用 class 避免傳遞 appBar 參數,AppBar 將不會出現。 但應該出現。

@override
  Widget build(BuildContext context) {
    return CommonScaffold(
      body: _createContent(),
    );
  }

如果我調用 class 將 AppBar 傳遞給 appBar 參數,則會出現 AppBar。

@override
  Widget build(BuildContext context) {
    return CommonScaffold(
      body: _createContent(),
      appBar: AppBar(
          title: const Text("TEST"),
      ),
    );
  }

問題在於我們有兩個appBarbody用於CommonScaffold 第一組是因為extends Scaffold而到來,第二組是通過在CommonScaffold上聲明兩個。

您可以通過運行此代碼段來檢查它在 OOP 上的工作方式。 在 dartPad 上 我正在更改名稱以更好地理解這個概念。

class Super {
  final int? a;
  final int? b;

  const Super({this.a, this.b});
}

class Common extends Super {
  final int? ca;
  final int b;

  const Common({this.ca, required this.b}) : super(a: ca ?? 10, b: b);
}

void main() {
  final c = Common(b: 1);
  print("supper a: ${c.a}"); // 10:  will refer supper class 
  print("Common a: ${c.ca}"); // null:  will refer common class 
}

現在為您解答,最好更改CommonScaffold的屬性名稱以避免與超級 class 沖突。

這是dartPad上的答案


class CommonScaffold extends Scaffold {
  final AppBar? cAppBar;

  final Widget? cBody;

  CommonScaffold({
    Key? key,
    this.cAppBar,
    this.cBody,
  }) : super(
            key: key,
            body: cBody,
            appBar: cAppBar ??
                AppBar(
                  title: Text("Default Appbar"),
                ));
}

class A extends StatelessWidget {
  const A({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      cBody: Text("body"),
    );
  }
}

如果您只想顯示或不顯示 appBar,則可以通過修改 bool 的值來顯示或不顯示欄來使用此示例

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: (showAppbar)? AppBar(
          title: const Text("Default Text"),
        ): AppBar(
          title: const Text("TEST"),
      ),
      body: Center(
        child: Text(
          'Hello, a!',
        ),
      ),
    );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM