簡體   English   中英

是否可以從 Scaffold 小部件中的 body 傳遞 AppBar?

[英]Is it possible to pass AppBar from body in Scaffold widget?

我有一個帶drawerScaffold小部件。 我需要在body顯示的屏幕有不同的AppBars (其中一些有PageView指示器,其中一些是單頁的,一些有徽標)。 所以我沒有將任何AppBar傳遞給我的Scaffold而是將它包含在我在body使用的小部件中。 但是抽屜和它沒有漢堡包圖標。

是否可以將此AppBar從我的body小部件傳遞到包含它的Scaffold

或者,如果有更好的小部件組合方式來解決這種情況,我想嘗試一下。

UPD

有一種很好的方式來顯示BottomSheet os SnackBar

Scaffold.of(context)
    .showSnackBar(SnackBar(content: Text('Processing Data')));

不幸的是, AppBar並非如此。

似乎您想要一個在切換頁面時保持不變的全局Scaffold 在這種情況下,您必須編寫自己的邏輯來顯示菜單按鈕:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, child) {
        // wrap a scaffold around the Navigator so that it is the same for all pages
        return Scaffold(
          body: AppScaffold(child: child),
          drawer: Drawer(),
        );
      },
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: buildLeadingAction(context),
        title: Text('Home'),
      ),
    );
  }
}

/// Makes it easier to access the outer scaffold with the drawer from any context
class AppScaffold extends InheritedWidget {
  const AppScaffold({Key key, @required Widget child})
      : assert(child != null),
        super(key: key, child: child);

  /// nullable
  static ScaffoldState of(BuildContext context) {
    return context
        .ancestorInheritedElementForWidgetOfExactType(AppScaffold)
        ?.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
  }

  @override
  bool updateShouldNotify(AppScaffold old) => false;
}

/// This is a simple method and not a widget
/// so that null can be returned if no AppScaffold with a drawer was found
Widget buildLeadingAction(BuildContext context) {
  final ScaffoldState appScaffold = AppScaffold.of(context);
  if (appScaffold != null && appScaffold.hasDrawer) {
    return IconButton(
      icon: const Icon(Icons.menu),
      onPressed: () => appScaffold.openDrawer(),
      tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
    );
  } else {
    return null;
  }
}

或者,您也可以將抽屜的Scaffold放置在頁面內,並使用GlobalKey訪問其ScaffoldState

暫無
暫無

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

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