简体   繁体   中英

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

After connecting my project to Firestore and creating collection, document, etc, when I try to print the name of a product at index 0, this is the error I am getting.

The following RangeError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#18c55): RangeError (index): Invalid value: Valid value range is empty: 0

I have read this similar question posted here but it does not solve my issue

Below is except of my code

class Home extends StatelessWidget {

Product menData;

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: _onBackPressed,
      child: Scaffold(
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.only(top: 10, left: 10, right: 10),
              child: FutureBuilder(
             future: FirebaseFirestore.instance.collection("products")
                      .doc("6di1OSBgwOjyLbPtl75g").collection("recent").get(),
            builder: (context, snapshot) {
              if(snapshot.connectionState == ConnectionState.waiting){
                return Center(
                  child: spinkit,
                );
              }
              menData = Product(
                image: snapshot.data.documents[0]["image"],
                name: snapshot.data.documents[0]["name"],
                price: snapshot.data.documents[0]["price"],
              );
              print(menData.name);

This is the model

import 'package:flutter/material.dart';

class Product {
  final String image;
  final String name;
  final double price;

  Product({@required this.image, @required this.name, @required this.price});

}

这是数据库截图

FutureBuilder tends to bury data type errors. It's most likely an issue within your call FirebaseFirestore.instance.collection("products").doc("6di1OSBgwOjyLbPtl75g").collection("recent").get(),

I'm guessing that some product is not loading with the proper types,

      final String image;
      final String name;
      final double price;  

Probably the double price is coming in as a int or something weird like that. I've diagnosed a few of these issues and they almost always present like your bug:

Swap out your view with this example's "snapshot view check". It will validate your error and display the correct one: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

List<Widget> children;
          if (snapshot.hasData) {
            children = <Widget>[
              Icon(
                Icons.check_circle_outline,
                color: Colors.green,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Result: ${snapshot.data}'),
              )
            ];
          } else if (snapshot.hasError) {
            children = <Widget>[
              Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Error: ${snapshot.error}'),
              )
            ];
          } else {
            children = <Widget>[
              SizedBox(
                child: CircularProgressIndicator(),
                width: 60,
                height: 60,
              ),
              const Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text('Awaiting result...'),
              )
            ];
          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: children,
            ),
          );

This error "Invalid value: Valid value range is empty: 0" happened because your list index value is null, but you are keep force to call the value out.

Try to temporary change this 3 lines to hardcode value:

image: snapshot.data.documents[0]["image"]
name: snapshot.data.documents[0]["name"]
price: snapshot.data.documents[0]["price"]

to 

image: 'hardcode'
name: 'harcode'
price: 'hardcode'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM