簡體   English   中英

上下文的顫振腳手架“不包含腳手架”

[英]Flutter scaffold of context giving "does not contain a Scaffold"

我在腳手架上有一個 appbar。

return Scaffold(
  appBar: styling.appBar(
      AppBar(
        leading: styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu),
      )
  ),
);

這是圖標按鈕:

  ClipRRect iconButton(VoidCallback onPressed, IconData icon) {
return ClipRRect(
  borderRadius: BorderRadius.circular(360),
  child : Material(
      color: Colors.transparent,
      child: IconButton(
        icon: Icon(
          icon,
          color: secondaryColor,
        ),
        onPressed: onPressed,
      )
  ),
);

}

這是為了替換打開抽屜的默認漢堡包圖標,當我單擊它時,出現此錯誤:

Scaffold.of() called with a context that does not contain a Scaffold.

這幾乎可以肯定,因為您的context實際上在 Scaffold 之外。 您的函數可能類似於以下內容:

Widget build(BuildContext context) {
  // ... other code up here

  return Scaffold(
    appBar: styling.appBar(AppBar(
      leading: styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu),
    )),
  );
}

這里的問題是context實際上 DID 來自不在 Scaffold 內的地方。 您在這里使用的context來自包裝build()函數的函數參數,它確實存在於 Scaffold 之外(因為這個build()是實際生成Scaffold )。

你需要做的是這樣的:

Widget build(BuildContext context) {
  // ... other code up here

  return Scaffold(
    appBar: styling.appBar(
      AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return styling.iconButton(() => Scaffold.of(context).openDrawer(), Icons.menu);
          },
        ),
      ),
    ),
  );
}

或者類似的東西。 原因是因為現在,在builder函數中,您實際上有一個新的context對象,該對象將實際存在於 Scaffold 中。

希望這很清楚。 如果沒有,我可以進一步解釋。

編輯1:簡單的解決方案

Builder(
  builder: (context) {
    return Scaffold(
      drawer: Drawer(),
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: () => Scaffold.of(context).openDrawer(),
        ),
      ),
    );
  },
)

暫無
暫無

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

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