dart dotsCount必须上级 Flutter 中的零错误

lmyy7pcs  于 2023-06-19  发布在  Flutter
关注(0)|答案(1)|浏览(98)

我试图在Flutter中发送HTTP请求,并在我的应用程序中显示结果。但我有一个错误。当我将dotsCount的值设置为10这样的数字时,不会发生此错误。
这是我的代码:

`import 'dart:convert';
import 'package:requests/home_page_free.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../../widgets/small_text.dart';

class HomePageBody extends StatefulWidget {
  const HomePageBody({super.key});

  @override
  State<HomePageBody> createState() => _HomePageBodyState();
}

class _HomePageBodyState extends State<HomePageBody> {
  PageController freeController = PageController(viewportFraction: 0.85);
  var _freeCurrentPageValue = 0.0;
  var _freeScaleFactor = 0.8;
  double _height = 320;

  List<MainFree> _free_items = [];
   
  @override
  void initState() {
    freeController.addListener(() {
      setState(() {
        _freeCurrentPageValue = freeController.page!;
      });
    });`
    freeItem();
    super.initState();
  }

  @override
  void dispose() {
    freeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Column(
            children: [
              Container(
              height: MediaQuery.of(context).size.height/3.6,
              child: PageView.builder(
                  controller: freeController,
                  itemCount: _free_items.length,
                  itemBuilder: (context, position){
                    return _freePageItem(position, _free_items[position]);
                  }
                  ),
              ),
              new DotsIndicator(
                dotsCount: _free_items.length,
                position: _freeCurrentPageValue ,
                decorator: DotsDecorator(
                  size: const Size.square(9.0),
                  activeSize: const Size(18.0, 9.0),
                  activeShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
                ),
              ),
            ]
        ),
      ),
    );
  }

  Widget _freePageItem(int index, MainFree free){
    return Stack(
      children: [
        Container(
          height: MediaQuery.of(context).size.height/6,
          margin: EdgeInsets.only(left: 5, right: 5),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: Colors.deepOrange,
              image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(
                      free.app_image
                  )
              )

          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            height: 110,
            margin: EdgeInsets.only(left: MediaQuery.of(context).size.width/20,
                right: MediaQuery.of(context).size.width/20,
                bottom: MediaQuery.of(context).size.height/28),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(MediaQuery.of(context).size.height/28),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Color(0xFFe8e8e8),
                  blurRadius: 5.0,
                  offset: Offset(5, 5),
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(-5, 0),
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(5, 0),
                ),
              ],
            ),
            child: Container(
              padding: EdgeInsets.only(
                  top: 10, right: 15, left: 15
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('title of data', style: TextStyle(fontSize: 15),),
                  SizedBox(height: MediaQuery.of(context).size.height/120,),
                  Text('des of data', style: TextStyle(fontSize: 12, color: Colors.black54),),
                  SizedBox(height: MediaQuery.of(context).size.height/130,),
                  Row(
                    children: [
                      //? yonma yon 5 ta icons yasab beradi
                      Wrap(children: List.generate((5), (index) => Icon(Icons.star,))),

                      //? Yulduzcha oldidagi textlar (4.5, 10, commit)
                      Row(
                        children: [
                          SizedBox(width: 10),
                          SmallText(text: "4.5"),
                          SizedBox(width: 10),
                          SmallText(text: "1287"),
                          SizedBox(width: 10),
                          SmallText(text: "comments"),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height/130,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.lock_clock, color: Colors.orange,),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.military_tech, color: Colors.tealAccent),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.time_to_leave, color: Colors.pink),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
  void freeItem() async{
    var url = Uri.https('www.geors.ir', '/api_free/', {'q': '{http}'});
    var response = await get(url);
    setState(() {
      var free_json = json.decode(utf8.decode(response.bodyBytes));
      for (var i in free_json){
        var free_items = MainFree(i['title'], i['app_image'], i['category'], i['tech_count'],  

        i['views'], i['meta_description']);
        _free_items.add(free_items);
      }
    });
  }
}

但它会引起这个错误:

`dotsCount must be superior to zero
'package:dots_indicator/src/dots_indicator.dart':
Failed assertion: line 31 pos 16: 'dotsCount > 0'`

出现此错误时,软件会在几秒钟后打开并工作。怎么修理???

nlejzf6q

nlejzf6q1#

您面临的问题是构建方法没有等待freeItem()方法完成
因此,构建方法以
free_items
length的第一个值0运行
解决方案是在build方法中放置一个等待小部件,直到**freeItem()**完成工作并获取数据。

试试这个:

import 'dart:convert';
import 'package:requests/home_page_free.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../../widgets/small_text.dart';

class HomePageBody extends StatefulWidget {
  const HomePageBody({super.key});

  @override
  State<HomePageBody> createState() => _HomePageBodyState();
}

class _HomePageBodyState extends State<HomePageBody> {
  PageController freeController = PageController(viewportFraction: 0.85);
  var _freeCurrentPageValue = 0.0;
  var _freeScaleFactor = 0.8;
  double _height = 320;
  bool isLoading=true;

  List<MainFree> _free_items = [];

  @override
  void initState() {
    freeController.addListener(() {
      setState(() {
        _freeCurrentPageValue = freeController.page!;
      });
    });
    
    freeItem();
    super.initState();
  }

  @override
  void dispose() {
    freeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: isLoading?CircularProgressIndicator():SingleChildScrollView(
        child: Column(
            children: [
              Container(
                height: MediaQuery
                    .of(context)
                    .size
                    .height / 3.6,
                child: PageView.builder(
                    controller: freeController,
                    itemCount: _free_items.length,
                    itemBuilder: (context, position) {
                      return _freePageItem(position, _free_items[position]);
                    }
                ),
              ),
              new DotsIndicator(
                dotsCount: _free_items.length,
                position: _freeCurrentPageValue,
                decorator: DotsDecorator(
                  size: const Size.square(9.0),
                  activeSize: const Size(18.0, 9.0),
                  activeShape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0)),
                ),
              ),
            ]
        ),
      ),
    );
  }

  Widget _freePageItem(int index, MainFree free) {
    return Stack(
      children: [
        Container(
          height: MediaQuery
              .of(context)
   
           .size
              .height / 6,
          margin: EdgeInsets.only(left: 5, right: 5),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: Colors.deepOrange,
              image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(
                      free.app_image
                  )
              )

          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            height: 110,
            margin: EdgeInsets.only(left: MediaQuery
                .of(context)
                .size
                .width / 20,
                right: MediaQuery
                    .of(context)
                    .size
                    .width / 20,
                bottom: MediaQuery
                    .of(context)
                    .size
                    .height / 28),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(MediaQuery
                  .of(context)
                  .size
                  .height / 28),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Color(0xFFe8e8e8),
                  blurRadius: 5.0,
                  offset: Offset(5, 5),
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(-5, 0),
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(5, 0),
                ),
              ],
            ),
            child: Container(
              padding: EdgeInsets.only(
                  top: 10, right: 15, left: 15
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('title of data', style: TextStyle(fontSize: 15),),
                  SizedBox(height: MediaQuery
                      .of(context)
                      .size
                      .height / 120,),
                  Text('des of data',
                    style: TextStyle(fontSize: 12, color: Colors.black54),),
                  SizedBox(height: MediaQuery
                      .of(context)
                      .size
                      .height / 130,),
                  Row(
                    children: [
//? yonma yon 5 ta icons yasab beradi
                      Wrap(children: List.generate((5), (index) =>
                          Icon(Icons.star,))),

//? Yulduzcha oldidagi textlar (4.5, 10, commit)
                      Row(
                        children: [
                          SizedBox(width: 10),
                          SmallText(text: "4.5"),
                          SizedBox(width: 10),
                          SmallText(text: "1287"),
                          SizedBox(width: 10),
                          SmallText(text: "comments"),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: MediaQuery
                      .of(context)
                      .size
                      .height / 130,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.lock_clock, color: Colors.orange,),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.military_tech, color: Colors.tealAccent),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                      Container(
                        child: Row(
                          children: [
                            Icon(Icons.time_to_leave, color: Colors.pink),
                            SizedBox(width: 5,),
                            SmallText(text: 'text')
                          ],
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  void freeItem() async {
    isLoading=true;
    var url = Uri.https('www.geors.ir', '/api_free/', {'q': '{http}'});
    var response = await get(url);
    setState(() {
      var free_json = json.decode(utf8.decode(response.bodyBytes));
      for (var i in free_json) {
        var free_items = MainFree(
            i['title'], i['app_image'], i['category'], i['tech_count'],

            i['views'], i['meta_description']);
        _free_items.add(free_items);
      }
      isLoading=false;
    });
  }
}

相关问题