flutter 范围错误(索引):无效值:有效值范围为空:0,,,谁能告诉我我的streambuilder方法有什么问题吗?

h5qlskok  于 2023-02-05  发布在  Flutter
关注(0)|答案(1)|浏览(144)

下面是错误:

Exception caught by widgets library ═══════════════════════════════════

The following RangeError was thrown building StreamBuilder\<QuerySnapshot\<Object?\>\>(dirty, state: \_StreamBuilderBaseState\<QuerySnapshot\<Object?\>, AsyncSnapshot\<QuerySnapshot\<Object?\>\>\>#5a321):

RangeError (index): Invalid value: Valid value range is empty: 0

下面是我的代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:emart_app/Controller/auth_controller.dart';
import 'package:emart_app/Controller/profile_controller.dart';
import 'package:emart_app/Services/firestore_services.dart';
import 'package:emart_app/consts/consts.dart';
import 'package:emart_app/consts/list.dart';
import 'package:emart_app/views/Auth%20Screen/login_screen.dart';
import 'package:emart_app/views/Profile%20Screen/Components(Profile)/details_card.dart';
import 'package:emart_app/views/Profile%20Screen/Components(Profile)/edit_profile_screen.dart';
import 'package:emart_app/widgets_common/bg_widget.dart';
import 'package:get/get.dart';

class ProfileScreen extends StatelessWidget {
  const ProfileScreen({super.key});

  @override
  Widget build(BuildContext context) {
    var controller = Get.put(ProfileController());
    return bgWidget(
        child: Scaffold(
            body: StreamBuilder(
                stream: FirestoreServies.getUser(currentUser!.uid),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (!snapshot.hasData) {
                    return const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation(redColor),
                      ),
                    );
                  } else {
                    var data = snapshot.data!.docs[0];
                    return SafeArea(
                        child: Column(
                      children: [
                        //edit profile section
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: const Align(
                              alignment: Alignment.topRight,
                              child: Icon(
                                Icons.edit,
                                color: whiteColor,
                              )).onTap(() {
                            controller.nameController.text = data['name'];
                            controller.passController.text = data['password'];

                            Get.to(() => EditProfileScreen(data: data));
                          }),
                        ),

                        //user details section
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          child: Row(
                            children: [
                              data['imageUrl'] == ''
                                  ? Image.asset(
                                      imgProfile3,
                                      width: 60,
                                      fit: BoxFit.cover,
                                    )
                                      .box
                                      .roundedFull
                                      .clip(Clip.antiAlias)
                                      .make()
                                  : Image.network(
                                      data['imageUrl'],
                                      width: 60,
                                      fit: BoxFit.cover,
                                    )
                                      .box
                                      .roundedFull
                                      .clip(Clip.antiAlias)
                                      .make(),
                              20.widthBox,
                              Expanded(
                                  child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  "${data['name']}"
                                      .text
                                      .fontFamily(semibold)
                                      .white
                                      .make(),
                                  "${data['email']}".text.white.make()
                                ],
                              )),
                              OutlinedButton(
                                  style: OutlinedButton.styleFrom(
                                      side:
                                          const BorderSide(color: whiteColor)),
                                  onPressed: () async {
                                    await Get.put(AuthController())
                                        .signOutMethod(context);
                                    Get.offAll(() => const LoginScreen());
                                  },
                                  child: logout.text
                                      .fontFamily(semibold)
                                      .white
                                      .make())
                            ],
                          ),
                        ),
                        10.heightBox,

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            detailsCard(
                                count: data['cart_count'],
                                title: "In Your Cart",
                                width: context.screenWidth / 3.4),
                            detailsCard(
                                count: data['wishlist_count'],
                                title: "In Your Wishlist",
                                width: context.screenWidth / 3.4),
                            detailsCard(
                                count: data['order_count'],
                                title: "Your Orders",
                                width: context.screenWidth / 3.4)
                          ],
                        ),
                        5.heightBox,
                        ListView.separated(
                                shrinkWrap: true,
                                itemBuilder: (context, index) {
                                  return ListTile(
                                    leading: Image.asset(
                                      profileButtonIcons[index],
                                      width: 22,
                                    ),
                                    title: profileButtonsList[index]
                                        .text
                                        .fontFamily(semibold)
                                        .color(darkFontGrey)
                                        .make(),
                                  );
                                },
                                separatorBuilder: (context, index) {
                                  return const Divider(
                                    color: lightGrey,
                                  );
                                },
                                itemCount: profileButtonsList.length)
                            .box
                            .rounded
                            .white
                            .margin(const EdgeInsets.all(12))
                            .padding(const EdgeInsets.symmetric(horizontal: 16))
                            .shadowSm
                            .make()
                            .box
                            .color(redColor)
                            .make()
                      ],
                    ));
                  }
                })));
  }
}
5gfr0r5j

5gfr0r5j1#

snapshot.data!.docs似乎为空。您可以使用for循环简单地循环它。并在索引中指定。snapshot.hasData仅检查值是否为非空,它不检查值是否为空。

if(snapshot.data!.docs.isNotEmpty){
    for(int i=0; i<snapshot.data!.docs; i++){
        final data = snapshot.data!.docs[i];
        return  SafeArea(child: AnyWidget(data: data));
    }
} else {
     return Text("List is empty");
}

相关问题