未处理的异常:错误状态:无元素
Posted
技术标签:
【中文标题】未处理的异常:错误状态:无元素【英文标题】:Unhandled Exception: Bad state: No element 【发布时间】:2021-12-30 21:09:24 【问题描述】:在我将图像添加到启动屏幕之前,我的构建工作正常,这时我开始收到 PhaseScript 错误。我不得不完全删除 ios 文件夹,重新创建它,然后再次进行必要的手动更改。现在,当我通过 android studio 在模拟器上运行构建时,一旦应用启动,就会出现此错误:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Bad state: No element
#0 List.first (dart:core-patch/growable_array.dart:339:5)
#1 main (package:globe_flutter/main.dart:19:25)
<asynchronous suspension>
屏幕上没有任何显示。我在main.dart
和tabBarView
中使用tabBar
来显示不同的屏幕。这是main.dart
:
var firstCamera;
Future<void> main() async
WidgetsFlutterBinding.ensureInitialized();
// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();
// Get a specific camera from the list of available cameras.
firstCamera = cameras.first;
await Firebase.initializeApp();
runApp(MyApp());
// void main() async
// WidgetsFlutterBinding.ensureInitialized();
// await Firebase.initializeApp();
// runApp(MyApp());
//
class MyApp extends StatelessWidget
const MyApp(Key? key) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'GLOBE',
debugShowCheckedModeBanner: false,
home: const MyHome(),
routes:
LoginScreen.id: (context) => LoginScreen(),
SignupScreen.id: (context) => SignupScreen(),
HomeScreen.id: (context) => HomeScreen()
,
);
class MyHome extends StatefulWidget
const MyHome(Key? key) : super(key: key);
@override
_MyHomeState createState() => _MyHomeState();
class _MyHomeState extends State<MyHome> with SingleTickerProviderStateMixin
late TabController _tabController;
@override
void initState()
super.initState();
_tabController = TabController(length: 5, vsync: this);
@override
void dispose()
super.dispose();
_tabController.dispose();
@override
Widget build(BuildContext context)
return Scaffold(
body: TabBarView(
children: [
HomeScreen(),
HomeScreen(),
TakePictureScreen(camera: firstCamera),
HomeScreen(),
ProfileScreen(username: "cjmofficial")
],
controller: _tabController
),
extendBody: true,
bottomNavigationBar: Container(
color: Colors.transparent,
padding: EdgeInsets.symmetric(vertical: 40, horizontal: 40),
child: ClipRRect(
clipBehavior: Clip.hardEdge,
borderRadius: BorderRadius.circular(50.0),
child: Container(
height: 55,
color: Colors.grey[200],
child: TabBar(
labelColor: Colors.teal[200],
unselectedLabelColor: Colors.blueGrey,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(color: Colors.teal),
insets: EdgeInsets.fromLTRB(50, 0, 50, 40)
),
indicatorColor: Colors.teal,
tabs: [
Tab(icon: Icon(Icons.home_outlined)),
Tab(icon: Icon(Icons.explore_outlined)),
Tab(icon: Icon(Icons.camera_alt_outlined)),
Tab(icon: Icon(Icons.movie_outlined)),
Tab(icon: Icon(Icons.person_outline))
],
controller: _tabController),
),
),
),
);
以及应该在TabBarView
中显示的第一个屏幕:
class HomeScreen extends StatefulWidget
const HomeScreen(Key? key) : super(key: key);
static const String id = "home_screen";
@override
_HomeScreenState createState() => _HomeScreenState();
class _HomeScreenState extends State<HomeScreen>
Color _likeButtonColor = Colors.black;
Widget _buildPost(String username, String imageUrl, String caption, String pfpUrl)
return Container(
color: Colors.white,
child: Column(
children: [
GestureDetector(
onTap: (),
child: Container(
height: 50,
color: Colors.deepOrangeAccent[100],
child: Row(
children: [
SizedBox(width: 5),
CircleAvatar(
child: ClipOval(
child: Image.network(
pfpUrl,
height: 40,
width: 40,
),
),
),
SizedBox(width: 10),
Icon(Icons.more_vert, size: 20),
SizedBox(width: 10),
Text(username, style: TextStyle(fontSize: 15))
],
),
),
),
Stack(
children: [
Image.asset("images/post_background.jpg"),
Padding(
padding: const EdgeInsets.all(20.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(imageUrl, fit: BoxFit.cover)),
),
],
),
Container(
height: 100,
child: Column(
children: [
const SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
onPressed: ()
setState(()
HapticFeedback.lightImpact();
);
,
icon: Icon(Icons.thumb_up_alt_outlined, size: 30)),
Text("l", style: TextStyle(fontSize: 30)),
IconButton(
onPressed: ()
setState(()
HapticFeedback.lightImpact();
GallerySaver.saveImage(imageUrl);
);
,
icon: Icon(Icons.ios_share, size: 30))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(caption, style: const TextStyle(fontSize: 15))
],
)
],
),
)
],
),
);
List<Post> listPosts = [];
fetchPosts() async
final userRef = FirebaseFirestore.instance.collection('users');
final QuerySnapshot result = await userRef.get();
result.docs.forEach((res) async
print(res.id);
QuerySnapshot posts = await userRef.doc(res.id).collection("posts").get();
posts.docs.forEach((res)
listPosts.add(Post.fromJson(res.data() as Map<String, dynamic>));
);
// Other method
// listPosts = posts.docs.map((doc) => Post.fromJson(doc.data() as Map<String, dynamic>)).toList();
setState(() );
);
setState(()
listPosts.sort((a, b) => a.postedDate.compareTo(b.postedDate));
);
pfpUrl(String username) async
// Get pfpUrl
String downloadURL = await FirebaseStorage.instance
.ref(username + "/profile_picture.png")
.getDownloadURL();
return downloadURL;
@override
void initState()
fetchPosts();
super.initState();
@override
Widget build(BuildContext context)
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(45.0),
child: AppBar(
leading:
Icon(Icons.monetization_on_outlined, color: Colors.blueGrey),
centerTitle: true,
title: Text("GLOBE", style: TextStyle(color: Colors.blueGrey)),
actions: [
Icon(Icons.search, color: Colors.blueGrey),
SizedBox(width: 10)
],
backgroundColor: Colors.tealAccent[100]),
),
body: ListView.builder(
itemCount: listPosts.length,
itemBuilder: (BuildContext context, int index)
// We retrieve the post at index « index »
final post = listPosts[index];
// Get name from id
var parts = post.id.split('_');
var username = parts[0].trim();
// Get pfpUrl
String pfpUrlString = "https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3";
return _buildPost(username, post.postUrlString, post.caption, pfpUrlString);
),
);
我是 Flutter 的新手,对此我所能理解的就是无法加载某些内容。我还运行了一个详细的构建,但它没有提供更多信息。如果有人可以帮助我理解这个问题,那就太好了。
【问题讨论】:
由于代码 sn-p 没有导入,我可以追踪line 19
错误的来源
抱歉...第 19 行是 firstCamera = cameras.first;
。那条线是为了得到我想要启动相机屏幕的相机。既然你指出了这一点,我意识到这个错误是因为模拟器没有相机哈哈。谢谢!
【参考方案1】:
ios模拟器没有摄像头所以在第19行,当firstCamera = cameras.first
被调用时,没有第一个摄像头。
【讨论】:
正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。以上是关于未处理的异常:错误状态:无元素的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:未处理的异常:错误状态:DocumentSnapshotPlatform中不存在字段
未处理的异常:错误状态:平台不允许使用不安全的 HTTP - usesClearTextTraffic 不起作用
Flutter:未处理的异常:错误状态:调用关闭后无法添加新事件(不一样的情况)