1

i have this code:

@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())));
                  },

shows me this error:

======== 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)

what does it mean by details, and how can I fix it

Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61

1 Answers1

1

You are trying to read ScaffoldMessenger on same context. this issue also happen calling MediaQuery. You can wrap with a Builder widget to get seprate context.

return MaterialApp(
  home: DefaultTabController(
    length: 3,
    child: Builder(
      builder: (context) {
        return Scaffold(
          appBar: AppBar(
            bottom: TabBar(
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • "on same context" of what? what do you mean by the same context, and what is the problem behind it? – Osama Mohammed Nov 19 '22 at 10:14
  • `ScaffoldMessenger.of(context).` will look up on the context tree, but here we've only one the `MaterialApp` context. – Md. Yeasin Sheikh Nov 19 '22 at 10:16
  • why only MaterialApp? what about Scaffold for example? please, I need an depth information, I know the solution – Osama Mohammed Nov 19 '22 at 10:18
  • *ScaffoldMessenger.of(context) is using a context not underneath (i.e. not a child of) MaterialApp. (And there is no ScaffoldMessenger to be found above.)* https://stackoverflow.com/a/71944586/10157127 – Md. Yeasin Sheikh Nov 19 '22 at 10:20