Home > database >  Why my ListView.builder doesn't return anything?
Why my ListView.builder doesn't return anything?

Time:03-08

I want to create a mobile application with Flutter, which reads news via an api. First time using Getx package to manage state. And I don't know why my news list is not generated

Here is my home page with

 final TopHeadLinesController topheadlinesController =
        Get.put(TopHeadLinesController());
Padding(
                  padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 20.0),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "L'actualité en ce moment",
                            style: TextStyle(
                              fontFamily: 'Segoe UI',
                              fontSize: 21.0,
                              color: mainHexColor.withOpacity(0.54),
                            ),
                          ),
                          Align(
                            alignment: Alignment(0.84, -0.84),
                            child: InkWell(
                                onTap: () => Get.to(AppRoutes.TOP_HEADLINES),
                                splashColor: secondColor,
                                borderRadius: BorderRadius.circular(32.0),
                                child: Icon(Icons.double_arrow_rounded,
                                    size: 25.0, color: iconHexColor)),
                          ),
                        ],
                      ),
                      Container(
                        margin: EdgeInsets.only(bottom: 50.0),
                        padding: EdgeInsets.only(top: 5.0),
                        height: 235.0,
                        child: Obx(() {
                           return LoadingOverlay(
                              topheadlinesController.isLoading,
                              child:  ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount:
                                    topheadlinesController.articlesList.length,
                                itemBuilder: (context, index) {
                                  //   log('ELEMENT : ${topheadlinesController.articlesList[index]} &&&&&&&  ${topheadlinesController.articlesList[index].title}');
                                  return ActuItem(
                                    article: topheadlinesController.articlesList[index],
                                  );
                                }), 
                              );
                        }),

                        ),
                    ],
                  ),
                ),
              

The TopHeadLinesController file

class TopHeadLinesController extends GetxController {
  var articlesList = [].obs;
  bool isLoading = true;
  @override
  void onInit() {
    fetchArticles();
    super.onInit();
  }

  void fetchArticles() async {
    var articles = await ApiRequest(url:'https://newsapi.org/v2/top-headlinescountry=fr&apiKey=API_KEY')
        .getData();  // which returns a  Future<List<Article>>

    if (articles != null) {
      articlesList.value = articles;
    
    }
  }
}

and the ActuItem file

class ActuItem extends StatelessWidget {
  Article article;
 

  ActuItem(
      {required this.article});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 250,
      margin: EdgeInsets.all(10.0),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          //boxShadow: [ shadow ],
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 1,
                blurRadius: 9,
                offset: Offset(0, 3))
          ]),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: GestureDetector(
              onTap: (() => Get.to(AppRoutes.DETAILS_NEWS)),
              child: _getChild(),
              // ),
            ),
          ),
          SizedBox(
            height: 7.0,
          ),
          Padding(
            padding: EdgeInsets.only(
              top: 10.0,
              left: 10.0,
              right: 10.0,
            ),
            child: Text(
              article.title,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style:
                  TextStyle(fontFamily: 'avenir', fontWeight: FontWeight.w800),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(10.0),
            child: Text(
              article.url,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontFamily: 'Segoe UI',
                color: mainHexColor,
              ),
            ),
          )
        ],
      ),
    );
  }

  _getChild() {
    //print(const String.fromEnvironment('API_KEY'));
    return Container(
      width: Get.width,
      height: Get.height / 1.8,
      child: Image.network(
        article.urlToImage!,
        fit: BoxFit.cover,
      ),
    );
  }
}

No error is generated, the call to the API passes without problem. I don't know what's wrong

CodePudding user response:

I know you said the API call doesn't show an error but from what you shared, that is an invalid URL. There needs to be a ? between headlines and country. Also you're never resetting isLoading to false after the API call.

Besides that, I suggest initializing your list to a RxList of type Article and not dynamic.

  var articlesList = <Article>[].obs;

If there's an issue with the data that getData returns it will throw an error at this line and provide more insight.

articlesList.value = articles;

Then print articlesList and the end of the function or step through it in the debugger to see how that list is being populated.

Your issue almost certainly lies with articlesList not being properly initialized in the fetchArticles function.

CodePudding user response:

Do check your targetSdkVersion 30 and compileSdkVersion 30 in app level build gradle file.

classpath 'com.android.tools.build:gradle:3.6.2' in project level build gradle file. // Reason: May be your gradle version is upadted or some issue with the compileSdk or targetSdk versions.

  • Related