skip to Main Content

Making a list with adding items to the database. After switching from main.dart to the page with a list, it does not open, it writes an error.enter image description here

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);


  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  late String _userToDo;
  List todoList = [];

  void initFirebase() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(Home());
  }

  @override
  void initState() {
    super.initState();

    initFirebase();

    todoList.addAll(['Milk', 'Car', 'Sugar']);
  }

  void _menuOpen() {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Menu'),),
          body: Row(
            children: [
              Padding(padding: EdgeInsets.only(left: 15)),
              ElevatedButton(onPressed: () {
                Navigator.pop(context);
                Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);
              },
                  child: Text('Home')),
              Padding(padding: EdgeInsets.only(left: 15)),
              Text('Home old')
            ],
          )
        );
      })
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        title: Text('Список дел'),
        actions: [
          IconButton(onPressed: _menuOpen,
              icon: Icon(Icons.menu_outlined),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: todoList.length,
          itemBuilder: (BuildContext context, int index){
            return Dismissible(
                key: Key(todoList[index]),
                child: Card(
                  child: ListTile(
                    title: Text(todoList[index]),
                      trailing: IconButton(
                        icon: Icon(Icons.delete_sweep,
                        color: Colors.redAccent,
                        ), onPressed: () {
                          setState(() {
                            todoList.removeAt(index);
                          });
                      },
                      )
                  ),
                ),
              onDismissed: (direction) {
                //  if(direction == DismissDirection.startToEnd)
                    setState(() {
                      todoList.removeAt(index);
                    });
              },
             );
          }
       ),
        floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.green,
        onPressed: () {
        showDialog(context: context, builder: (BuildContext context){
          return AlertDialog(
          title: Text('Добавить'),
          content: TextField(
           onChanged: (String value){
             _userToDo = value;
        },
        ),
            actions: [
              ElevatedButton(onPressed: (){

                FirebaseFirestore.instance.collection('items').add({'item': _userToDo});

                Navigator.of(context).pop();
              }, child: Text('Добавить')
              )
            ],
          );
        });
    },
    child: Icon(Icons.add_comment_outlined,
    color: Colors.white,
    ),
    ),
    );
  }
}

Everyone knows the error.

The following assertion was thrown building Home(state:
_HomeState#17f50): No MediaQuery widget ancestor found.

Scaffold widgets require a MediaQuery widget ancestor. The specific
widget that could not find a MediaQuery ancestor was: Scaffold dirty
state: ScaffoldState#4d9ee(lifecycle state: initialized, tickers:
tracking 2 tickers) The ownership chain for the affected widget is:
"Scaffold ← Home ← [root]"

No MediaQuery ancestor could be found starting from the context that
was passed to MediaQuery.of(). This can happen because you have not
added a WidgetsApp, CupertinoApp, or MaterialApp widget (those widgets
introduce a MediaQuery), or it can happen if the context you use comes
from a widget above those widgets.


Set according to your advice. Navigation and pop-up window stopped working.

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);


  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  late String _userToDo;
  List todoList = [];

  void initFirebase() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(Home());
  }

  @override
  void initState() {
    super.initState();

    initFirebase();

    todoList.addAll(['Milk', 'Car', 'Sugar']);
  }

  void _menuOpen() {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Menu'),),
          body: Row(
            children: [
              Padding(padding: EdgeInsets.only(left: 15)),
              ElevatedButton(onPressed: () {
                Navigator.pop(context);
                Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);
              },
                  child: Text('Home')),
              Padding(padding: EdgeInsets.only(left: 15)),
              Text('Home old')
            ],
          )
        );
      })
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        title: Text('Список дел'),
        actions: [
          IconButton(onPressed: _menuOpen,
              icon: Icon(Icons.menu_outlined),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: todoList.length,
          itemBuilder: (BuildContext context, int index){
            return Dismissible(
                key: Key(todoList[index]),
                child: Card(
                  child: ListTile(
                    title: Text(todoList[index]),
                      trailing: IconButton(
                        icon: Icon(Icons.delete_sweep,
                        color: Colors.redAccent,
                        ), onPressed: () {
                          setState(() {
                            todoList.removeAt(index);
                          });
                      },
                      )
                  ),
                ),
              onDismissed: (direction) {
                //  if(direction == DismissDirection.startToEnd)
                    setState(() {
                      todoList.removeAt(index);
                    });
              },
             );
          }
       ),

        floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.green,
        onPressed: () {
        showDialog(context: context, builder: (BuildContext context){
          return AlertDialog(
          title: Text('Добавить'),
          content: TextField(
           onChanged: (String value){
             _userToDo = value;
        },
        ),
            actions: [
              ElevatedButton(onPressed: (){

                FirebaseFirestore.instance.collection('items').add({'item': _userToDo});

                Navigator.of(context).pop();
              }, child: Text('Добавить')
              )
            ],
          );
        });
    },
    child: Icon(Icons.add_comment_outlined,
    color: Colors.white,
    ),
    ),
      ),
    );
  }
}

The following assertion was thrown while handling a gesture: No
MaterialLocalizations found.

Home widgets require MaterialLocalizations to be provided by a
Localizations widget ancestor. The material library uses Localizations
to generate messages, labels, and abbreviations.

To introduce a MaterialLocalizations, either use a MaterialApp at the
root of your application to include them automatically, or add a
Localization widget with a MaterialLocalizations delegate.

The specific widget that could not find a MaterialLocalizations
ancestor was: Home state: _HomeState#8899d The ancestors of this
widget were: : [root] renderObject: RenderView#1dbbb

2

Answers


  1. Part of the error says: This can happen because you have not added a WidgetsApp, CupertinoApp, or MaterialApp widget.

    So in your Build method, you can wrap your Scaffold with a MaterialApp() and it should work.

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(...),
      );
    }
     
    
    Login or Signup to reply.
  2.   void initFirebase() async {
        WidgetsFlutterBinding.ensureInitialized();
        await Firebase.initializeApp();
        runApp(Home());
      }
    

    With that runApp call, you are removing your entire widget tree and replacing it with a tree rooted at a Home widget. This means that you are unable to access the MaterialApp widget that is presumably built by your App widget elsewhere in your app.

    To fix this, move the first two lines of this method to your main method before runApp, and remove the entire method from the Home widget.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search