簡體   English   中英

使用上下文調用的 Mediaquery.of 不包含 mediaquery 錯誤

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

我在 flutter “Mediaquery.of() 使用不包含 mediaquery 的上下文調用”中有一個錯誤我不明白為什么 mediaquery 不起作用,因為我在 materialapp 中這樣調用它:MediaQuery.of(context) .size.height 並且錯誤僅在模擬器上。 如果我的 main.dart 編碼正確(代碼結構),請你說我。 謝謝

這是我的代碼:

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;
    }
  }
}

為您的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(),
                      ),
                    );
                  }
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

然后在您的 MaterialApp 中使用您的Home小部件

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

您正在從錯誤的位置訪問MediaQuery.of(context).size.width

嘗試做這樣的事情:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM