调用showModalBottomSheet报错:No MediaQuery widget found.
来源:6-16 拍照APP开发-图片获取与图片展示【实战尝鲜】
liusiqian0209
2019-10-13
课程5-16,点击右下角按钮的时候报错
代码如下:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(PhotoPage());
class PhotoPage extends StatefulWidget {
@override
_PhotoPageState createState() => _PhotoPageState();
}
class _PhotoPageState extends State<PhotoPage> {
File _image;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Photo App',
theme:
ThemeData(primarySwatch: Colors.blue, brightness: Brightness.light),
home: Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child:
_image == null ? Text('No image selected.') : Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: _pickImage,
tooltip: '选择图片',
child: Icon(Icons.add_a_photo),
),
),
);
}
_pickImage() {
showModalBottomSheet(
context: context,
builder: (context) => Container(
height: 160,
child: Column(
children: <Widget>[
_listItem('拍照', true),
_listItem('从相册选择', false)
],
),
));
}
_listItem(String title, bool camera) {
return GestureDetector(
child: ListTile(
leading: Icon(camera ? Icons.camera_alt : Icons.photo_library),
title: Text(
title,
textDirection: TextDirection.ltr,
),
onTap: () => getImage(camera),
),
);
}
Future getImage(bool camera) async {
var image = await ImagePicker.pickImage(
source: camera ? ImageSource.camera : ImageSource.gallery);
setState(() {
_image = image;
});
}
}
另外,如果build方法最外层返回的Scaffold不使用MaterialApp包裹的话,也会报类似的错误
写回答
1回答
-
CrazyCodeBoy
2019-10-14
使用MediaQuery.of时要留意它所属的widget不能直接和runApp接触,需要用一个带有MaterialApp的widget包裹一下这样才能使用MediaQuery.of,这里用到了showModalBottomSheet,而showModalBottomSheet中调用了MediaQuery.of所以会报这个错误。
解决方案,可以参考课程中的方式,在使用showModalBottomSheet的widget外在包一层widget。
112022-08-28
相似问题