Неудачное утверждение: логическое выражение не должно быть нулевым. Изначально экран загрузки называется - PullRequest
0 голосов
/ 09 мая 2020

Мой код следующий:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  List<CategoryModel> categories = new List<CategoryModel>();
  List<ArticleModel> articles = new List<ArticleModel>();
  bool _loading = true;

  getNews() async{
    News newsClass = News();
    await newsClass.getNews();
    articles = newsClass.news;
    setState(() {
      _loading = false;
    });
  }

  @override
  void initState() {
    getNews();
    categories = getCategories();
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("News"),
            Text("App", style: TextStyle(
                color: Colors.blueAccent
            ),)
          ],
        ),
        centerTitle: true,
        elevation: 0.0,
      ),

      body: _loading ? Center(
          child: CircularProgressIndicator(),
      ) : SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            children: <Widget>[

              /// Categories
              Container(
                height: 70,
                child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: categories.length,
                    itemBuilder: (context, index){
                      return CategoryTile(
                        imageUrl: categories[index].imageUrl,
                        categoryName: categories[index].categoryName,
                      );
                    }),
              ),

              /// Blog
              Container(
                padding: EdgeInsets.only(top: 16),
                child: ListView.builder(
                    itemCount: articles.length,
                    shrinkWrap: true,
                    physics: ClampingScrollPhysics(),
                    itemBuilder: (context, index){
                      return BlogTile(
                        imageUrl: articles[index].urlToImage,
                        title: articles[index].title,
                        desc: articles[index].description,
                      );
                    }),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class CategoryTile extends StatelessWidget {

  final imageUrl, categoryName;
  CategoryTile({this.imageUrl, this.categoryName});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){

      },
      child: Container(
        margin: EdgeInsets.only(right: 16),
        child: Stack(
          children: <Widget>[
            ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: CachedNetworkImage(
                  imageUrl: imageUrl, width: 120, height: 60, fit: BoxFit.cover,)
            ),
            Container(
              alignment: Alignment.center,
              width: 120, height: 60,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Colors.black26,
              ),
              child: Text(categoryName, style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.w500
              ),),
            )
          ],
        ),
      ),
    );
  }
}

class BlogTile extends StatelessWidget {

  final String imageUrl, title, desc;
  BlogTile({@required this.imageUrl,@required this.title,@required this.desc});
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.network(imageUrl)
          ),
          SizedBox(height: 8,),
          Text(title, style: TextStyle(
              fontSize: 17, color: Colors.black87, fontWeight: FontWeight.w500
          ),),
          SizedBox(height: 8,),
          Text(desc, style: TextStyle(
              color: Colors.black54
          ),)
        ],
      ),
    );
  }
}
Когда я запускаю код, он показывает экран загрузки, который не гаснет, контент, который я хочу отобразить, не отображается. Пожалуйста, помогите, предоставив свой ценный ответ. Заранее спасибо.

Я получаю следующую ошибку:

E / flutter (5339): [ОШИБКА: flutter / lib / ui / ui_dart_state. cc (157) ] Необработанное исключение: неудачное утверждение: логическое выражение не должно быть нулевым

1 Ответ

0 голосов
/ 09 мая 2020

Поскольку вы инициализируете свою переменную _loading внутри первого оператора initState. Вы также можете инициализировать его напрямую при объявлении.

Вот так: bool _loading = true;

Попробуйте использовать следующий код:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  List<CategoryModel> categories = new List<CategoryModel>();
  List<ArticleModel> articles = new List<ArticleModel>();
  bool _loading = true;

  getNews() async{
    News newsClass = News();
    await newsClass.getNews();
    articles = newsClass.news;
  }

  @override
  void initState() {
    getNews();
    categories = getCategories();
    setState(() {
      _loading = false;
    });
    super.initState();
  }

Надеюсь, это поможет.

...