Niamul Hasan
Niamul Hasan

Reputation: 146

Generate a static List from a async method in dart/flutter

This is my initState() code.

void initState() {
    super.initState();
    data = [
      BarChartGroupData(
        x: 0,
        barsSpace: 4,
        barRods: [
          BarChartRodData(
              color: normal,
              y: 5,
              borderRadius: const BorderRadius.all(Radius.zero)),
          BarChartRodData(
              color: normal,
              y: 4,
              borderRadius: const BorderRadius.all(Radius.zero))
        ],
      ),
    ];
  }

I need to return a normal list barRods: from this Future async method,

static Future<List<Map>> getDayList(int year, int month) async {
    Database database = await DatabaseInit.openDb();
    return await database.rawQuery(
        'SELECT DISTINCT day FROM SalahRecord WHERE year = $year AND month = $month');
  }

how do I return a normal list from getDayList()

Upvotes: 1

Views: 3620

Answers (1)

wxker
wxker

Reputation: 1896

You cannot get a List directly from Future as you normally would with usual data types. You have 3 ways to retrieve the List from the future:

  1. async/await
void someFunction() async {
    List<Map> dayList = await getDayList(?, ?);
    ...
}
  1. .then
getDayList(?, ?).then((List<Map> dayList) {
    ...
});
  1. FutureBuilder (https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html)
Future<List<Map>> dayList;

void initState() {
    super.initState();
    data = [
      BarChartGroupData(
        x: 0,
        barsSpace: 4,
        barRods: [
          BarChartRodData(
              color: normal,
              y: 5,
              borderRadius: const BorderRadius.all(Radius.zero)),
          BarChartRodData(
              color: normal,
              y: 4,
              borderRadius: const BorderRadius.all(Radius.zero))
        ],
      ),
    ];
    dayList = getDayList(?, ?)
}

Widget build(BuildContext context) {
    return ...
        FutureBuilder(
            future: dayList,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                ...
            }
        )
        ...
}

Upvotes: 4

Related Questions