【问题标题】:MediaQuery.of() called with a context that does not contain a MediaQuery. error使用不包含 MediaQuery 的上下文调用 MediaQuery.of()。错误
【发布时间】:2020-08-09 23:22:30
【问题描述】:

我正在尝试在互联网的帮助下制作一个应用程序。该应用程序正在从图库中拍照,并将其发送到我的服务器。当我准备好代码时,出现了一个错误。

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

它是说没有 MediaQuery。这是我的代码

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,
            ),
          ],
        ),
      ),
    );
  }
}

我不知道如何解决这个问题,因为这个 MediaQuery 对我来说是新的。如何解决此错误?

【问题讨论】:

    标签: android ios flutter dart


    【解决方案1】:

    你需要提供MaterialApp,你可以把MaterialApp放在UploadImageDemo上面
    代码sn-p

    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(),
        );
      }
    }
    

    工作演示

    完整代码

    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,
                ),
              ],
            ),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 2020-12-16
      • 2020-11-22
      • 1970-01-01
      • 2020-07-27
      • 2020-02-17
      相关资源
      最近更新 更多