Home > database >  No ScaffoldMessenger widget found. TabBarDemo widgets require a ScaffoldMessenger widget ancestor
No ScaffoldMessenger widget found. TabBarDemo widgets require a ScaffoldMessenger widget ancestor

Time:11-19

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

CodePudding user response:

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(
  • Related