【问题标题】:No ScaffoldMessenger widget found. TabBarDemo widgets require a ScaffoldMessenger widget ancestor未找到 ScaffoldMessenger 小部件。 TabBarDemo 小部件需要一个 ScaffoldMessenger 小部件祖先
【发布时间】:2022-11-19 18:18:14
【问题描述】:

我有这个代码:

@override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: DefaultTabController(
            length: 3,
            child: Scaffold(
              drawer: SideBar(),
              appBar: AppBar(
                bottom: TabBar(
                  onTap: (index) {
                       ScaffoldMessenger.of(context).
                    showSnackBar(SnackBar(content: Text(index.toString())));
                  },

向我显示此错误:

======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
No ScaffoldMessenger widget found.

TabBarDemo widgets require a ScaffoldMessenger widget ancestor.
The specific widget that could not find a ScaffoldMessenger ancestor was: TabBarDemo
  state: _TabBarDemoState#50b4e
The ancestors of this widget were: 
  : [root]
    renderObject: RenderView#47398

Typically, the ScaffoldMessenger widget is introduced by the MaterialApp at the top of your application widget tree.

When the exception was thrown, this was the stack: 
#0      debugCheckHasScaffoldMessenger.<anonymous closure> (package:flutter/src/material/debug.dart:151:7)
#1      debugCheckHasScaffoldMessenger (package:flutter/src/material/debug.dart:162:4)
#2      ScaffoldMessenger.of (package:flutter/src/material/scaffold.dart:146:12)
#3      _TabBarDemoState.build.<anonymous closure> (package:tab/main.dart:23:38)
#4      _TabBarState._handleTap (package:flutter/src/material/tabs.dart:1136:19)
#5      _TabBarState.build.<anonymous closure> (package:flutter/src/material/tabs.dart:1261:21)
#6      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)

详细信息是什么意思,我该如何解决

【问题讨论】:

    标签: flutter scaffold


    【解决方案1】:

    您正在尝试在同一上下文中阅读 ScaffoldMessenger。这个问题也发生在调用 MediaQuery 时。您可以使用 Builder 小部件包装以获得单独的上下文。

    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Builder(
          builder: (context) {
            return Scaffold(
              appBar: AppBar(
                bottom: TabBar(
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2020-11-23
      • 2021-05-18
      • 2021-10-08
      • 2021-03-31
      相关资源
      最近更新 更多