Exception Caught By Widgets Library error in Flutter
Asked Answered
I

6

5

I have this application in Flutter. It has two classes it spouses to generate a list of notes.

This is the main class, the MyApp class:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:notesgenerator/sala.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override

  Widget build(BuildContext context) {

    List<Sala> locs = [
      Sala(note: 'Study', noteDes: 'from 6pm ~ 8pm'),
      Sala(note: 'Work', noteDes: 'from 8pm ~ 9pm'),
      Sala(note: 'Play', noteDes: 'from 9pm ~ 9:30pm'),
      Sala(note: 'Eat', noteDes: 'from 9:30pm ~ 10pm'),
    ];

    return Scaffold(
      appBar: AppBar(
        title: Text('NoteIndex'),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: 10,
          itemBuilder: (context, index) {
            return Card(
              child: ListTile(
                onTap: () {},
                title: (Text(locs[index].note)),
              ),
            );
          }),
    );}}

This is the class that stores the data, the Sala class:

class Sala {
  String note;
  String noteDes;
  Sala({this.note, this.noteDes});
}

When I try to run it, I get this:

I/flutter (21388): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (21388): The following assertion was thrown building MyApp:
I/flutter (21388): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter (21388): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter (21388): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter (21388): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter (21388): The context used was:
I/flutter (21388):   Scaffold
I/flutter (21388): 
I/flutter (21388): The relevant error-causing widget was:
I/flutter (21388):   MyApp file:///F:/FlutterProjects/notesgenerator/lib/main.dart:6:23
I/flutter (21388): 
I/flutter (21388): When the exception was thrown, this was the stack:
I/flutter (21388): #0      MediaQuery.of (package:flutter/src/widgets/media_query.dart:798:5)
I/flutter (21388): #1      ScaffoldState.didChangeDependencies (package:flutter/src/material/scaffold.dart:1993:50)
I/flutter (21388): #2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4376:12)
I/flutter (21388): #3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
I/flutter (21388): #4      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
I/flutter (21388): #5      Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
I/flutter (21388): #6      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
I/flutter (21388): #7      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
I/flutter (21388): #8      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
I/flutter (21388): #9      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
I/flutter (21388): #10     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
I/flutter (21388): #11     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
I/flutter (21388): #12     RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1028:16)
I/flutter (21388): #13     RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:999:5)
I/flutter (21388): #14     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:942:17)
I/flutter (21388): #15     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2412:19)
I/flutter (21388): #16     RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:941:13)
I/flutter (21388): #17     WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:819:7)
I/flutter (21388): #18     WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:804:7)
I/flutter (21388): #27     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
I/flutter (21388): #28     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
I/flutter (21388): #29     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
I/flutter (21388): (elided 8 frames from package dart:async and package dart:async-patch)
I/flutter (21388): 
I/flutter (21388): ════════════════════════════════════════════════════════════════════════════════════════════════════

If you can help, I will really appreciate it! If you have any questions, please let me know in the comments!

Insubordinate answered 17/2, 2021 at 9:55 Comment(1)
Your code has bad formatting and this is not editable because as stackoverflow guidelines mentionned you should explain your problem, give examples and context which you didn't do. Please give us detail.Rame
S
7

You need to wrap your Scaffold with

MaterialApp()

because this is the widget that introduces MediaQuery

Changes in build of MyApp:

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
       ...
      ),
    );
Seleucia answered 17/2, 2021 at 10:15 Comment(0)
W
6

Solution

itemCount: locs.length instead of itemCount: 10 .

For those who are curious about the Reason , read the follwing :

Take a look at your List :

 List<Sala> locs = [
  Sala(note: 'Study', noteDes: 'from 6pm ~ 8pm'),
  Sala(note: 'Work', noteDes: 'from 8pm ~ 9pm'),
  Sala(note: 'Play', noteDes: 'from 9pm ~ 9:30pm'),
  Sala(note: 'Eat', noteDes: 'from 9:30pm ~ 10pm'),
];

It's clearly that the Length of your List is 3.

But, here in your ListViewBuilder :

itemCount: 10,

You are setting a static Value of 10, this will tells the builder that there are 10 items to be returned, and that exceed the actual length of your list, to make it clear , You are returning 10 items of Card , while your list only contains 3 item, this will try to create 10 items which is does not exist from the start in your list and of course it will return an Index error when the iterator return the last item of your List,which means it will return the error at the 4th index since you have only 3 items.

Wilie answered 29/12, 2021 at 20:36 Comment(0)
Z
5

Wrap your scaffold with MaterialApp

    return MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
    visualDensity: VisualDensity.adaptivePlatformDensity,
  ),
  home: Scaffold(),
);
Zebada answered 17/2, 2021 at 11:9 Comment(1)
This answer is a repeat of Nitesh's answer which was made less than an hour earlier.Schistosome
A
3

in my case, i was using "expanded" widget under "stack" widget, i removed "expanded" widget, and it worked. I dont know how relative to your situation, but we got the same error.

enter image description here

Adelladella answered 22/12, 2023 at 21:47 Comment(0)
F
0

You can add above your "MaterialApp" a list of all "Provider" or "BLoC". Here is an example in "main.dart":

@override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [

        //Provider for theme
        ChangeNotifierProvider<ThemeProvider>(create: (_) => ThemeProvider()),

        //Some BLoC
        BlocProvider<SomeBloc>(
          create: (context) => SomeBloc(),
        ),
        BlocProvider<AnotherBloc>(
          create: (context) => AnotherBloc(),
        ),
      ],
      builder: (context, child) => Builder(builder: (context) {
        // Just wrap the MaterialApp you have
        return MaterialApp(
            home: const SomeHomePage(),
          },
Forebear answered 23/6, 2023 at 23:1 Comment(0)
A
-1

If you are using Getxbuilder, Then follow the note:

First thing, You have to verify your Getxbuilder<YOUR_VIEW_CONTROLER> name of your every Getxbuilder view controller.

That's the only issue when I get the error.

Follow the code:

 GetBuilder<**RecentMatchListViewController**>(
                            builder: (_) => recentMatchListViewController!
                                        .recentMatchListModel!
                                        .data![index]
                                        .result ==
                                    null
                                ? progressIndicator(1)
                                : Text(
                                    recentMatchListViewController!
                                        .recentMatchListModel!
                                        .data![index]
                                        .result
                                        .toString(),
                                    style: redHeadingTextStyle(),
                                    textAlign: TextAlign.center,
                                  ),
                          )

The RecentMatchListViewController maybe changes to another view controller like

GetBuilder<**UpcomingMatchListViewController**>(
                            builder: (_) => recentMatchListViewController!
                                        .recentMatchListModel!
                                        .data![index]
                                        .result ==
                                    null
                                ? progressIndicator(1)
                                : Text(
                                    recentMatchListViewController!
                                        .recentMatchListModel!
                                        .data![index]
                                        .result
                                        .toString(),
                                    style: redHeadingTextStyle(),
                                    textAlign: TextAlign.center,
                                  ),
                          )

This is due to some copy past work and also imported the files by mismatch.

Andryc answered 23/3, 2022 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.