从dart / flutter中的异步方法生成静态列表

问题描述 投票:0回答:1

这是我的initState()代码。

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))
        ],
      ),
    ];
  }

我需要从此Future异步方法中返回普通列表barRods:

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');
  }

如何从getDayList()返回普通列表

flutter dart async-await
1个回答
0
投票

您无法像通常使用常规数据类型那样直接从Future中获取列表。您有3种方法可以从将来检索列表:

  1. 异步/等待
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) {
                ...
            }
        )
        ...
}

热门问题
推荐问题
最新问题