ios 未行程的例外状况:错误状态:无元素

mhd8tkvw  于 12个月前  发布在  iOS
关注(0)|答案(2)|浏览(94)

我的构建工作正常,直到我在启动屏幕上添加了一个图像,这时我开始得到一个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.darttabBarView中使用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和所有我能理解的是,这是一些无法加载。我也用verbose运行了一个构建,但它没有给予更多的信息。如果有人能帮助我理解这个问题,那就太好了。

trnvg8h3

trnvg8h31#

Ios模拟器没有摄像头,所以在第19行,当firstCamera = cameras.first被调用时,没有第一个摄像头。

8iwquhpp

8iwquhpp2#

我在Flutter Web中也遇到了这个错误,只是调用相机。首先没有任何设置。

_cameraController = CameraController(cameras.first, ResolutionPreset.max);

相关问题