gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:19:53 27 4
gpt4 key购买 nike

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

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对我来说是新的。我该如何解决此错误?

最佳答案

您需要提供MaterialApp,可以将MaterialApp放在UploadImageDemo上方
程式码片段

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(),
);
}
}
工作演示
enter image description here
完整的代码
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,
),
],
),
),
);
}
}

关于android - 使用不包含MediaQuery的上下文调用MediaQuery.of()。错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63332287/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com