简体   繁体   English

使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。 错误

[英]MediaQuery.of() called with a context that does not contain a MediaQuery. error

I am trying to make an app with some help from the internet.我正在尝试在互联网的帮助下制作一个应用程序。 The app is taking a picture from a gallery and it will send it to my server.该应用程序正在从图库中拍照,并将其发送到我的服务器。 When I got the code ready, there appeared an error.当我准备好代码时,出现了一个错误。

I/flutter (11233): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11233): The following assertion was thrown building UploadImageDemo(dirty, state:
I/flutter (11233): UploadImageDemoState#e27ba):
I/flutter (11233): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter (11233): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter (11233): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter (11233): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter (11233): The context used was:
I/flutter (11233):   UploadImageDemo

it is saying that there isn't a MediaQuery.它是说没有MediaQuery。 And here is my code这是我的代码

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

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

class UploadImageDemo extends StatefulWidget {

  UploadImageDemo() : super();

  final String title = "Upload Image Demo";

  @override
  UploadImageDemoState createState() => UploadImageDemoState();
}

class UploadImageDemoState extends State<UploadImageDemo> {

  //
  static final String uploadEndPoint =
      'http://localhost/flutter_test/upload_image.php';
  Future<File> file;
  String status = '';
  String base64Image;
  File tmpFile;
  String errMessage = 'Error Uploading Image';

  chooseImage() {
    setState(() {
      file = ImagePicker.pickImage(source: ImageSource.gallery);
    });
    setStatus('');
  }

  setStatus(String message) {
    setState(() {
      status = message;
    });
  }

  startUpload() {
    setStatus('Uploading Image...');
    if (null == tmpFile) {
      setStatus(errMessage);
      return;
    }
    String fileName = tmpFile.path.split('/').last;
    upload(fileName);
  }

  upload(String fileName) {
    http.post(uploadEndPoint, body: {
      "image": base64Image,
      "name": fileName,
    }).then((result) {
      setStatus(result.statusCode == 200 ? result.body : errMessage);
    }).catchError((error) {
      setStatus(error);
    });
  }

  Widget showImage() {

    return FutureBuilder<File>(
      future: file,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            null != snapshot.data) {
          tmpFile = snapshot.data;
          base64Image = base64Encode(snapshot.data.readAsBytesSync());
          return Flexible(
            child: Image.file(
              snapshot.data,
              fit: BoxFit.fill,
            ),
          );
        } else if (null != snapshot.error) {
          return const Text(
            'Error Picking Image',
            textAlign: TextAlign.center,
          );
        } else {
          return const Text(
            'No Image Selected',
            textAlign: TextAlign.center,
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text("Upload Image Demo"),
      ),
      body: Container(
        padding: EdgeInsets.all(30.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            OutlineButton(
              onPressed: chooseImage,
              child: Text('Choose Image'),
            ),
            SizedBox(
              height: 20.0,
            ),
            showImage(),
            SizedBox(
              height: 20.0,
            ),
            OutlineButton(
              onPressed: startUpload,
              child: Text('Upload Image'),
            ),
            SizedBox(
              height: 20.0,
            ),
            Text(
              status,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.green,
                fontWeight: FontWeight.w500,
                fontSize: 20.0,
              ),
            ),
            SizedBox(
              height: 20.0,
            ),
          ],
        ),
      ),
    );
  }
}

I don't have an idea on how to fix this, because this MediaQuery is new to me.我不知道如何解决这个问题,因为这个 MediaQuery 对我来说是新的。 How do i fix this error?我该如何解决这个错误?

You need to provide MaterialApp , you can put MaterialApp above UploadImageDemo需要提供MaterialApp ,可以把MaterialApp放在UploadImageDemo上面
code snippet代码片段

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

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Upload Image Demo',
      theme: ThemeData(       
        primarySwatch: Colors.blue,       
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: UploadImageDemo(),
    );
  }
}

working demo工作演示

在此处输入图像描述

full code完整代码

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Upload Image Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: UploadImageDemo(),
    );
  }
}

class UploadImageDemo extends StatefulWidget {
  UploadImageDemo() : super();

  final String title = "Upload Image Demo";

  @override
  UploadImageDemoState createState() => UploadImageDemoState();
}

class UploadImageDemoState extends State<UploadImageDemo> {
  //
  static final String uploadEndPoint =
      'http://localhost/flutter_test/upload_image.php';
  Future<File> file;
  String status = '';
  String base64Image;
  File tmpFile;
  String errMessage = 'Error Uploading Image';

  chooseImage() {
    setState(() {
      file = ImagePicker.pickImage(source: ImageSource.gallery);
    });
    setStatus('');
  }

  setStatus(String message) {
    setState(() {
      status = message;
    });
  }

  startUpload() {
    setStatus('Uploading Image...');
    if (null == tmpFile) {
      setStatus(errMessage);
      return;
    }
    String fileName = tmpFile.path.split('/').last;
    upload(fileName);
  }

  upload(String fileName) {
    http.post(uploadEndPoint, body: {
      "image": base64Image,
      "name": fileName,
    }).then((result) {
      setStatus(result.statusCode == 200 ? result.body : errMessage);
    }).catchError((error) {
      setStatus(error);
    });
  }

  Widget showImage() {
    return FutureBuilder<File>(
      future: file,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            null != snapshot.data) {
          tmpFile = snapshot.data;
          base64Image = base64Encode(snapshot.data.readAsBytesSync());
          return Flexible(
            child: Image.file(
              snapshot.data,
              fit: BoxFit.fill,
            ),
          );
        } else if (null != snapshot.error) {
          return const Text(
            'Error Picking Image',
            textAlign: TextAlign.center,
          );
        } else {
          return const Text(
            'No Image Selected',
            textAlign: TextAlign.center,
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    print(size);
    return Scaffold(
      appBar: AppBar(
        title: Text("Upload Image Demo"),
      ),
      body: Container(
        padding: EdgeInsets.all(30.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            OutlineButton(
              onPressed: chooseImage,
              child: Text('Choose Image'),
            ),
            SizedBox(
              height: 20.0,
            ),
            showImage(),
            SizedBox(
              height: 20.0,
            ),
            OutlineButton(
              onPressed: startUpload,
              child: Text('Upload Image'),
            ),
            SizedBox(
              height: 20.0,
            ),
            Text(
              status,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.green,
                fontWeight: FontWeight.w500,
                fontSize: 20.0,
              ),
            ),
            SizedBox(
              height: 20.0,
            ),
          ],
        ),
      ),
    );
  }
}

暂无
暂无

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

相关问题 未检测到键盘。 MediaQuery.of(context).viewInsets.bottom 总是返回 0.0 - Keyboard not being detected. MediaQuery.of(context).viewInsets.bottom always returns 0.0 Flutter Get.width 或初始化 MediaQuery.of(context).size 在 Release 模式下不起作用 - Flutter Get.width or initialize MediaQuery.of(context).size not working in Release mode 当我将 MediaQuery.of(context).padding.top 与 appBar 一起使用时,它返回 0.0。 这是为什么? - MediaQuery.of(context).padding.top is returning 0.0 when I'm using it with appBar. Why is that? Flutter MediaQuery.of(context).size.width 检查设备大小总是在 iOS 模拟器中返回相同的错误值 - Flutter MediaQuery.of(context).size.width to check device-size always returns same wrong value in the iOS Simulator 在 flutter 中使用 MediaQuery 的高度和宽度大小时出错 - Error while using MediaQuery for size of height and width in flutter Flutter:未找到 MediaQuery 小部件祖先 - Flutter: No MediaQuery widget ancestor found MediaQuery 无法获取宽度和高度 - MediaQuery fail to get width and height Flutter 错误:(Webview) Media Query.of() 使用不包含媒体查询的上下文调用 - Flutter Error:(Webview) Media Query.of() called with a context that does not contain a media query 如何使用 MediaQuery 计算高度和宽度? - how to use calculate height and width using MediaQuery? 未处理的异常:未找到 MediaQuery 小部件 - 颤动 ShowModalButtonSheet - Unhandled Exception: No MediaQuery widget found - flutter ShowModalButtonSheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM