构建Builder(dirty)时引发了以下RangeError:

时间:2020-01-23 19:45:49

标签: firebase flutter dart

上下文:

我正在尝试使用Flutter创建一个动态滑块,它将获得构成漫画的图像的Firebase URL,并将其放入CarouselSlider中,我处理了空和空的返回值,但是它一直显示错误从我的应用程序中的无效索引中获取。

错误:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following RangeError was thrown building Builder(dirty):
RangeError (index): Invalid value: Valid value range is empty: 0

The relevant error-causing widget was: 
  Builder file:///Users/murilopazzini/Documents/Projs/SchoolsOut_Dev/schools_out/lib/components/hqSlider.dart:55:24
When the exception was thrown, this was the stack: 
#0      List.[] (dart:core-patch/growable_array.dart:149:60)
#1      _hqSliderState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:schools_out/components/hqSlider.dart:72:61)
#2      Builder.build (package:flutter/src/widgets/basic.dart:6757:41)
#3      StatelessElement.build (package:flutter/src/widgets/framework.dart:4291:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Home.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:schools_out/pages/comicsPage.dart';
import 'package:schools_out/components/hqSlider.dart';
import 'package:schools_out/entities/comics.dart';
import 'package:schools_out/entities/comicsPage.dart';

class Homepage extends StatefulWidget {
  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage>
    with SingleTickerProviderStateMixin {
  Animation animation;
  AnimationController animationController;

  @override
  void initState() {
    // super.initState();
    animationController =
        new AnimationController(duration: Duration(seconds: 200), vsync: this);
    animation =
        IntTween(begin: 0, end: photos.length - 1).animate(animationController)
          ..addListener(() {
            setState(() {
              index = animation.value;
            });
          });

    animationController.repeat(period: Duration(seconds: 20));
  }

  int index = 0;
  List<String> photos = [
    'https://i.ibb.co/kc1mjTW/abduc-a-o-55-1.png',
    'https://i.ibb.co/nmFdgs8/abduc-a-o-55-2.jpg'
  ];

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ComicsList(Comics clist) => InkWell(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ComicsReadingPage(
                      comics: clist,
                    )),
          );
        },
        child: PopularHq(
          image: clist.pages[0].image,
          name: clist.name,
        ));
    bestm(BMovies movie) => HqWidget(
          image: movie.Image,
        );

    final comics_scroll = Container(
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        physics: BouncingScrollPhysics(),
        child: Row(
          children: comicsList.map((cl) => ComicsList(cl)).toList(),
        ),
      ),
    );

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          iconTheme: new IconThemeData(color: Colors.blueGrey[600]),
          centerTitle: true,
          title: Text(
            "Schools Out",
            style: TextStyle(color: Colors.blueGrey[600], fontSize: 28),
          ),
          backgroundColor: Colors.white,
          //    leading:Icon(Icons.notifications,color: Colors.red,) ,
          //  toolbarOpacity: 0,
        ),
        drawer: new Drawer(
          child: ListView(
            children: <Widget>[
              new UserAccountsDrawerHeader(
                accountName: new Text('Test User'),
                accountEmail: new Text('testemail@test.com'),
                currentAccountPicture: new CircleAvatar(
                  backgroundImage: new NetworkImage('http://i.pravatar.cc/300'),
                ),
              ),
              new ListTile(
                title: new Text('Test Navigation'),
                onTap: () {
                  Navigator.of(context).pop();
                  Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (BuildContext context) => new Homepage()));
                },
              ),
            ],
          ),
        ),
        body: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            children: <Widget>[
              Container(
                color: Colors.white,
                child: Column(
                  children: <Widget>[
                    ImageData(photos[index]),

                    //  TopMovies()
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "HQ's",
                      style: TextStyle(
                          fontWeight: FontWeight.w900,
                          fontSize: 16,
                          color: Colors.blueGrey),
                    ),
                    SizedBox(
                      width: 180,
                    ),
                  ],
                ),
              ),
              hqSlider(),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Tirinhas",
                      style: TextStyle(
                          fontWeight: FontWeight.w900,
                          fontSize: 16,
                          color: Colors.blueGrey),
                    ),
                    SizedBox(
                      width: MediaQuery.of(context).size.width * 0.65,
                    ),
                    Text(
                      "See All",
                      style: TextStyle(
                          fontWeight: FontWeight.w900,
                          fontSize: 16,
                          color: Colors.blueGrey),
                    )
                  ],
                ),
              ),
              comics_scroll
            ],
          ),
        ));
  }
}

class ImageData extends StatelessWidget {
  String image;

  ImageData(this.image);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      height: 180,
      decoration: BoxDecoration(
          image: DecorationImage(
            image: NetworkImage(image),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.0)),
      child: Align(
        alignment: Alignment.bottomCenter,
      ),
    );
  }
}

class HqWidget extends StatelessWidget {
  final String image;

  HqWidget({Key key, this.image});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ClipOval(
        child: Container(
          height: 60,
          width: 60,
          decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage(image),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(12.0),
              boxShadow: [
                BoxShadow(
                    offset: Offset(0.5, 1.0),
                    blurRadius: 5,
                    color: Colors.white)
              ]),
        ),
      ),
    );
  }
}

////////////////////////////////////////////

class PopularHq extends StatelessWidget {
  String image, name;

  PopularHq({this.image, this.name});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: InkWell(
        child: Column(
          children: <Widget>[
            Container(
              height: 140,
              width: 100,
              decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage(image),
                    fit: BoxFit.cover,
                  ),
                  borderRadius: BorderRadius.circular(6.0),
                  boxShadow: [
                    BoxShadow(
                        offset: Offset(0.5, 1.0),
                        blurRadius: 5,
                        color: Colors.white)
                  ]),
            ),
            Container(
              //width: 100,
              //height: 40,
              child: Text(
                name,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    color: Colors.white),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

////////////////////////////////////////////



final List<Comics> comicsList = [
  Comics('Teste', 1, [
    ComicsPage('https://i.ibb.co/nmFdgs8/abduc-a-o-55-2.jpg', 1),
    ComicsPage('https://i.ibb.co/kc1mjTW/abduc-a-o-55-1.png', 2),
  ]),
  Comics('Teste 2', 2, [
    ComicsPage('https://i.ibb.co/nmFdgs8/abduc-a-o-55-2.jpg', 1),
    ComicsPage('https://i.ibb.co/kc1mjTW/abduc-a-o-55-1.png', 2),
  ]),
  Comics('Teste 3', 3, [
    ComicsPage('https://i.ibb.co/nmFdgs8/abduc-a-o-55-2.jpg', 1),
    ComicsPage('https://i.ibb.co/kc1mjTW/abduc-a-o-55-1.png', 2),
  ]),
];

class BMovies {
  String Image;
  int Boxc;

  BMovies(this.Image);
}

hqSlider.dart(错误源)

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:schools_out/pages/comicsPage.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:schools_out/entities/comicsPage.dart';
import 'package:schools_out/entities/comics.dart';
import 'dart:async';

class hqSlider extends StatefulWidget {
  @override
  _hqSliderState createState() => _hqSliderState();
}

class _hqSliderState extends State<hqSlider> {
  Future getComics() async {
    var firestore = Firestore.instance;

    QuerySnapshot qn = await firestore.collection("comics").getDocuments();

    return qn.documents;
  }

  @override
  Widget build(BuildContext context) {
    List<Comics> hqList = new List<Comics>();

    return FutureBuilder(
      future: getComics(),
      builder: (_, snapshot) {
        if (snapshot.data == null) {
          return Center(
            child: Text("Loading ..."),
          );
        } else if(snapshot.data.length > 0){
          hqList.clear();
          List<ComicsPage> pagesForThisHq = new List<ComicsPage>();

          snapshot.data.forEach((element) {

            element.data['pages'].forEach((page) {
              pagesForThisHq.add(ComicsPage(page['image'].toString(), page['page']));
            });

            hqList.add(
                Comics(element.data['name'], element.data['edition'], pagesForThisHq));
            pagesForThisHq.clear();
          });

          return CarouselSlider(
              autoPlay: true,
              viewportFraction: 0.9,
              aspectRatio: 2.4,
              enlargeCenterPage: false,
              items: hqList.map((hq) {
                return Builder(
                  builder: (BuildContext context) {
                    return Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        child: GestureDetector(onTap: () {
                          Navigator.push<Widget>(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ComicsReadingPage(
                                comics: hq,
                              ),
                            ),
                          );
                        }),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image: NetworkImage(hq.pages[0].image),
                                fit: BoxFit.cover),
                            borderRadius: BorderRadius.circular(12),
                            boxShadow: [
                              BoxShadow(
                                  offset: Offset(0.2, 1.0),
                                  blurRadius: 2,
                                  color: Colors.grey)
                            ]),
                      ),
                    );
                  },
                );
                //////
              }).toList());
        } else {
          return Center(
            child: Text("No Content ..."),
          );
        }
      },
    );
  }
}

类Comics.dart和ComicsPage.dart

import 'package:schools_out/entities/comicsPage.dart';

class Comics {
  List<ComicsPage> pages;
  String name;
  int edition;

  Comics(this.name, this.edition, this.pages);
}

class ComicsPage {
  String image;
  int page;

  ComicsPage(this.image, this.page);
}

1 个答案:

答案 0 :(得分:0)

通过运行flutter clean

可以轻松解决以上错误

此代码上还有第二个错误,这是由hqSlider.dart中的这一行代码引起的索引错误:

pagesForThisHq.clear();

像JS一样,Flutter会存储数据引用,而不是副本,因此当我清除此数组时,绑定到hqList的副本也会受到影响,从而导致索引错误。