【问题标题】:Generate a static List from a async method in dart/flutter从 dart/flutter 中的异步方法生成静态列表
【发布时间】:2020-04-09 20:38:20
【问题描述】:

这是我的 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】:

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

    1. 异步/等待
    void someFunction() async {
        List<Map> dayList = await getDayList(?, ?);
        ...
    }
    
    1. .那么
    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) {
                    ...
                }
            )
            ...
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多