简体   繁体   English

使用上下文调用的 Mediaquery.of 不包含 mediaquery 错误

[英]Mediaquery.of called with a context does not contain a mediaquery error

I have an error in flutter "Mediaquery.of() called with a context that does not contain a mediaquery" I Don't understand why mediaquery doesn't work because i have called it in materialapp like that: MediaQuery.of(context).size.height and the error is only on the emulator.我在 flutter “Mediaquery.of() 使用不包含 mediaquery 的上下文调用”中有一个错误我不明白为什么 mediaquery 不起作用,因为我在 materialapp 中这样调用它:MediaQuery.of(context) .size.height 并且错误仅在模拟器上。 And please can you say me if my main.dart is correctly coded (structure of code).如果我的 main.dart 编码正确(代码结构),请你说我。 Thanks谢谢

Here is my code:这是我的代码:

import 'package:flutter/material.dart';
import 'login.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:flutter_app/home.dart';
import 'package:flutter_app/globals.dart' as globals;
import 'package:awesome_page_transitions/awesome_page_transitions.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyApp_State createState() {
    return MyApp_State();
  }
}

class MyApp_State extends State<MyApp> {
  @override
  final appTitle = 'WINACOIN';

  String mail;
  String pass;

  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'WINACOIN',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          fontFamily: 'Azonix',
        ),
        home: Scaffold(
            appBar: new AppBar(
              title: new Text(appTitle),
            ),
            body: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.blue[400],Colors.blue[600],Colors.blue[800]],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight),
              ),
              child :
              Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      margin : const EdgeInsets.only(bottom:20),
                      child: Text('JEU 100 % GRATUIT 100 % GAGNANT',style: TextStyle(color: Colors.white,fontSize: 15,fontWeight: FontWeight.w500)),
                    ),
                    Container(
                      margin : const EdgeInsets.only(bottom:20),
                      child: Text('GAGNEZ DES CADEAUX ET DES EUROS',style: TextStyle(color: Colors.white,fontSize: 15,fontWeight: FontWeight.w500)),
                    ),
                    RaisedButton(
                      textColor: Colors.white,
                      color: Colors.green,
                      child: Text('COMMENCER',style: TextStyle(color: Colors.white,fontSize: 15,fontWeight: FontWeight.w500)),
                      onPressed: () async {
                        bool islog = await isconnect();
                        if (islog==false) {
                          Navigator.push(
                            context,
                            AwesomePageRoute(
                              transitionDuration: Duration(milliseconds: 1000),
                              exitPage: widget,
                              enterPage: LoginPage(),
                              transition: RotateUpTransition(),
                            ),
                          );
                        }
                        else {
                          Navigator.push(
                            context,
                            AwesomePageRoute(
                              transitionDuration: Duration(milliseconds: 1000),
                              exitPage: widget,
                              enterPage: HomePage(),
                              transition: RotateUpTransition(),
                            ),
                          );
                        }
                      },
                    )
                  ],
                ),
              ),
            )
        )
    );
  }
  Future <bool> isconnect() async {
    // Create storage

    final storage = new FlutterSecureStorage();

// Read value

    mail = await storage.read(key: "e");
    pass = await storage.read(key: "p");

    if (mail!=null && pass!=null) {

      var url = 'https://www.easytrafic.fr/game_app/login.php';

      // Store all data with Param Name.
      var data = {'email': mail, 'password': pass};

      // Starting Web API Call.
      var response = await http.post(url, body: json.encode(data),headers: {'content-type': 'application/json','accept': 'application/json'});

      print(json.decode(response.body));
      // Getting Server response into variable.

      Map <String,dynamic> map = json.decode(response.body);

      // If the Response Message is Matched.
      if (map["status"] == 1) {
        // l'email et le mot de passe sont correct
        final storage = new FlutterSecureStorage();

        await storage.write(key: "i", value: map["id_membre"]);
        await storage.write(key: "e", value: mail);
        await storage.write(key: "p", value: pass);
        await storage.write(key: "t", value: map["jwt"]);

        globals.id_membre=map["id_membre"];
        globals.token=map["jwt"];
        globals.balance=double.parse(map["balance"]);
        globals.points=map["nb_points"];
        print("la connexion a réussi avec les identifiants");

        return true;
      }
      else {
        // l'email et mot de passe stocké ne permettent pas de se connecter
        // rediriger vers la fenêtre de login
        print("mauvais identifiants");
        return false;
      }
    }
    else {
      // email et password n'existe pas
      print("email et password vide");
      return false;
    }
  }
}

Create a Widget for your Home为您的Home创建一个小部件

class Home extends StatelessWidget {
  final String appTitle;

  const Home({Key key, this.appTitle}) : super(key: key);
  @override
  Widget build() {
    return Scaffold(
      appBar: new AppBar(
        title: new Text(appTitle),
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Colors.blue[400], Colors.blue[600], Colors.blue[800]],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(bottom: 20),
                child: Text('JEU 100 % GRATUIT 100 % GAGNANT',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.w500)),
              ),
              Container(
                margin: const EdgeInsets.only(bottom: 20),
                child: Text('GAGNEZ DES CADEAUX ET DES EUROS',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.w500)),
              ),
              RaisedButton(
                textColor: Colors.white,
                color: Colors.green,
                child: Text('COMMENCER',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.w500)),
                onPressed: () async {
                  bool islog = await isconnect();
                  if (islog == false) {
                    Navigator.push(
                      context,
                      AwesomePageRoute(
                        transitionDuration: Duration(milliseconds: 1000),
                        exitPage: widget,
                        enterPage: LoginPage(),
                        transition: RotateUpTransition(),
                      ),
                    );
                  } else {
                    Navigator.push(
                      context,
                      AwesomePageRoute(
                        transitionDuration: Duration(milliseconds: 1000),
                        exitPage: widget,
                        enterPage: HomePage(),
                        transition: RotateUpTransition(),
                      ),
                    );
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

Then use your Home widget in your MaterialApp然后在您的 MaterialApp 中使用您的Home小部件

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title: 'Flutter Demo', home: Home(appTitle:"Title"));
  }
}

You are accessing the MediaQuery.of(context).size.width from a wrong place.您正在从错误的位置访问MediaQuery.of(context).size.width

Try doing something like this:尝试做这样的事情:

import 'package:flutter/material.dart';

class CommonThings {
  static Size size;
}

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'MediaQuery Demo',
      theme: new ThemeData(
        primarySwatch: Colors.red,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    print('Width of the screen: ${size.width}');
    return new Container();
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用不包含 MediaQuery 的上下文调用 MediaQuery.of() - MediaQuery.of() called with a context that does not contain MediaQuery MediaQuery.of()使用不包含MediaQuery的上下文调用 - MediaQuery.of() called with a context that does not contain a MediaQuery Flutter 错误:使用不包含 MediaQuery 的上下文调用 MediaQuery.of() - Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery 使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。 错误 - MediaQuery.of() called with a context that does not contain a MediaQuery. error 在使用不包含 MediaQuery 的上下文调用的 flutter MediaQuery.of() 中出现错误 - Getting Error in flutter MediaQuery.of() called with a context that does not contain a MediaQuery (使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。)错误 - (MediaQuery.of() called with a context that does not contain a MediaQuery.) error Flutter 错误:使用不包含 MediaQuery 的上下文调用 MediaQuery.of() - Flutter Error : MediaQuery.of() called with a context that does not contain a MediaQuery 使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。 (紧急援助) - MediaQuery.of() called with a context that does not contain a MediaQuery. (emergency aid) 使用不包含 MediaQuery 的上下文(来自 MaterialApp)调用 MediaQuery.of() - MediaQuery.of() called with a context (from MaterialApp) that does not contain a MediaQuery 在 MaterialApp 内部。 使用不包含 MediaQuery 的上下文调用 MediaQuery.of() - Inside of MatterialApp. MediaQuery.of() called with a context that does not contain a MediaQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM