Home > Blockchain >  how can use future in the listview flutter?
how can use future in the listview flutter?

Time:11-15

I have future function and I want show this in the listview.seprator, but the listview do not get the future value. how can i fix this? this is my code: my hive class:

@HiveType(typeId: 3)
class TaskCat  extends HiveObject{

  @HiveField(0)
   String catName;

  @HiveField(1)
  int userId;

  @HiveField(2)
   User? user;

  TaskCat(this.catName,this.user,this.userId);
}

This is my function:

Future<List> showCategoryInHome()  async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  var taskCatBox = await Hive.openBox('taskCat');
  var filtertaskCat = taskCatBox.values
      .where(
          (TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
      .toList();
  return filtertaskCat;
}

and this is my listview code:

FutureBuilder(
  future: controller.showCategoryInHome(),
  builder: (context, snapshot) {
    Future<List> test = controller.showCategoryInHome();
    return ListView.separated(
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      itemCount: 11 ,  // here currently I set the fix value but I want the length of my list
      itemBuilder: (context, index) {
        return TextButton(
          onPressed: () {

          },
          child:  Text(
         test[index].[catName], // and here not working too bucouse the list is future
            style: normalTextForCategory,
          ),
        );
      },
      separatorBuilder:
          (BuildContext context, int index) {
        return const VerticalDivider(
          width: 15,
          color: Colors.transparent,
        );
      },
    );
  },
)

CodePudding user response:

Try this:

FutureBuilder<List>(
        future: controller.showCategoryInHome(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                List data = snapshot.data ?? [];

                return ListView.separated(
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemCount:data.length,
                  itemBuilder: (context, index) {
                    return TextButton(
                      onPressed: () {},
                      child: Text(
                        data[index]['catName'],
                        style: normalTextForCategory,
                      ),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return const VerticalDivider(
                      width: 15,
                      color: Colors.transparent,
                    );
                  },
                );
              }
          }
        },
      ),

CodePudding user response:

Inside your Future you have builder, where you can access to your future when it ready via snapshot.

I've added the precise type where to make the use of Futurebuilder easier.

Future<List<TaskCat>> showCategoryInHome()  async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  var taskCatBox = await Hive.openBox('taskCat');
  var filtertaskCat = taskCatBox.values
      .where(
          (TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
      .toList();
  return filtertaskCat;
}

And adjust your Futurebuilder to the following:

FutureBuilder<List<TaskCat>>(
  future: controller.showCategoryInHome(),
  builder: (context, snapshot) {
    // Check if your future has finished
    if(snapshot.hasData) {
      // Here you have the result of your future, which is a List<TaskCat>
      final tasks = snapshot.data; 
      return ListView.separated(
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemCount: tasks.length,
        itemBuilder: (context, index) {
          return TextButton(
            onPressed: () {

            },
            child:  Text(
              tasks[index].catName,
              style: normalTextForCategory,
            ),
          );
        },
        separatorBuilder:
            (BuildContext context, int index) {
          return const VerticalDivider(
            width: 15,
            color: Colors.transparent,
          );
        },
      );
    } else {
      // Here you can show e.g. a CircularProgressIndicator
      return SizedBox();
    }
  },
)
  • Related