showMaterialBanner method Null safety

ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> showMaterialBanner(
  1. MaterialBanner materialBanner
)

Shows a MaterialBanner across all registered Scaffolds.

A scaffold can show at most one material banner at a time. If this function is called while another material banner is already visible, the given material banner will be added to a queue and displayed after the earlier material banners have closed.

To remove the MaterialBanner with an exit animation, use hideCurrentMaterialBanner or call ScaffoldFeatureController.close on the returned ScaffoldFeatureController. To remove a MaterialBanner suddenly (without an animation), use removeCurrentMaterialBanner.

See ScaffoldMessenger.of for information about how to obtain the ScaffoldMessengerState.

Here is an example of showing a MaterialBanner when the user presses a button.
To create a local project with this code sample, run:
flutter create --sample=material.ScaffoldMessengerState.showMaterialBanner.1 mysample

Implementation

ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> showMaterialBanner(MaterialBanner materialBanner) {
  _materialBannerController ??= MaterialBanner.createAnimationController(vsync: this)
    ..addStatusListener(_handleMaterialBannerStatusChanged);
  if (_materialBanners.isEmpty) {
    assert(_materialBannerController!.isDismissed);
    _materialBannerController!.forward();
  }
  late ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason> controller;
  controller = ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>._(
    // We provide a fallback key so that if back-to-back material banners happen to
    // match in structure, material ink splashes and highlights don't survive
    // from one to the next.
    materialBanner.withAnimation(_materialBannerController!, fallbackKey: UniqueKey()),
    Completer<MaterialBannerClosedReason>(),
        () {
      assert(_materialBanners.first == controller);
      hideCurrentMaterialBanner(reason: MaterialBannerClosedReason.hide);
    },
    null, // MaterialBanner doesn't use a builder function so setState() wouldn't rebuild it
  );
  setState(() {
    _materialBanners.addLast(controller);
  });
  _updateScaffolds();
  return controller;
}