当前位置: 首页 > 知识库问答 >
问题:

Flutter:将future作为int传递给图表

通寂离
2023-03-14

我正在做一个情绪检查应用程序使用flutter,其中用户选择了5个表情符号之一来告诉他们的心情。我想用数据表情符号显示一个PieChart vs num天它已经被选择了。问题是,我必须从sqflite数据库中获取数据,以获得numOfDays一个特定的表情符号被选中,它将是未来的类型,但图表不能采取未来,我试图使用async-await,但它似乎不起作用。

E/flutter (27721): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'int'
E/flutter (27721): #0      _MoodChartState.initData (package:pro_app/journal/view/mood_chart.dart:36:24)
E/flutter (27721): #1      _AsyncAwaitCompleter.start (dart:async/runtime/libasync_patch.dart:49:6)
E/flutter (27721): #2      _MoodChartState.initData (package:pro_app/journal/view/mood_chart.dart:31:16)
E/flutter (27721): #3      _MoodChartState.initState (package:pro_app/journal/view/mood_chart.dart:58:5)
E/flutter (27721): #4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3846:58)
E/flutter (27721): #5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
E/flutter (27721): #6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (27721): #7      Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (27721): #8      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #9      Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #10     StatelessElement.update (package:flutter/src/widgets/framework.dart:3796:5)
E/flutter (27721): #11     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #12     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #13     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #14     ProxyElement.update (package:flutter/src/widgets/framework.dart:4006:5)
E/flutter (27721): #15     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #16     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #17     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #18     ProxyElement.update (package:flutter/src/widgets/framework.dart:4006:5)
E/flutter (27721): #19     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #20     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:4601:32)
E/flutter (27721): #21     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4992:17)
E/flutter (27721): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #23     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #24     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #25     StatefulElement.update (package:flutter/src/widgets/framework.dart:3894:5)
E/flutter (27721): #26     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #27     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #28     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #29     ProxyElement.update (package:flutter/src/widgets/framework.dart:4006:5)
E/flutter (27721): #30     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #31     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #32     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #33     StatefulElement.update (package:flutter/src/widgets/framework.dart:3894:5)
E/flutter (27721): #34     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #35     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4883:14)
E/flutter (27721): #36     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #37     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #38     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #39     StatelessElement.update (package:flutter/src/widgets/framework.dart:3796:5)
E/flutter (27721): #40     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #41     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4883:14)
E/flutter (27721): #42     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
E/flutter (27721): #43     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (27721): #44     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (27721): #45     StatefulElement.update (package:flutter/src/widgets/framework.dart:3894:5)
E/flutter (27721): #46     Element.updateChild (package:flutter/src/wid
class Mood {
  int _moodID;
  int _emojiID;
  int _actID;
  int _moodDay;
  int _moodMonth;
  int _moodYear;

  Mood(this._emojiID, this._moodDay, this._moodMonth, this._moodYear,
      this._actID);

  Mood.withId(this._moodID, this._emojiID, this._moodDay, this._moodMonth,
      this._moodYear, this._actID);

  int get moodID => _moodID;
  int get emojiID => _emojiID;
  int get actID => _actID;
  int get moodDay => _moodDay;
  int get moodMonth => _moodMonth;
  int get moodYear => _moodYear;

// can define setters as well

  Map<String, int> toMap() {
    var map = Map<String, int>();
    if (_moodID != null) {
      map['moodId'] = _moodID;
    }
    map['emojiId'] = _emojiID;
    map['actId'] = _actID;
    map['moodDay'] = _moodDay;
    map['moodMonth'] = _moodMonth;
    map['moodYear'] = _moodYear;
    return map;
  }

  Mood.fromMap(Map<String, int> map) {
    this._moodID = map['moodId'];
    this._emojiID = map['emojiId'];
    this._actID = map['actId'];
    this._moodDay = map['moodMap'];
    this._moodMonth = map['moodMonth'];
    this._moodYear = map['moodYear'];
  }
}

*数据库文件

import 'package:path/path.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io';

import '../models/mood_model.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();
  factory DatabaseHelper() => _instance;

  final String tableName = "moodTable";
  final String colMoodId = "moodId";
  final String colEmojiId = "emojiId";
  final String colActId = "actId";
  final String colMoodDay = "moodDay";
  final String colMoodMonth = "moodMonth";
  final String colMoodYear = "moodYear";

  static Database _db;

  Future<Database> get db async {
    if (_db == null) {
      return initDb();
    }
    return _db;
  }

  DatabaseHelper.internal();

  Future<Database> initDb() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "mood.db");
    var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return ourDb;
  }

  void _onCreate(Database db, int version) async {
    await db.execute(
        "CREATE TABLE moodTable (moodId INTEGER PRIMARY KEY, emojiId INTEGER, actId INTEGER, moodDay INTEGER, moodMonth INTEGER, moodYear INTEGER)");
    print("Table Created");
  }

  // insert
  Future<int> saveMood(Mood mood) async {  
    var dbClient = await this.db;
    int result = await dbClient.insert("$tableName", mood.toMap());
    print('Saved');
    return result;

  }



  // to get number of mood days
  Future<List<Map<String, dynamic>>> listOfMoods() async {
    Database db = await this.db;
    var result = await db.query(tableName, orderBy: '$colMoodId ASC');
    return result;
  }

  Future<int> numOfMoodDays(int emojiID) async {
    Database db = await this.db;
    var result = await db.query(tableName,
        orderBy: '$colMoodId ASC',
        where: '$colEmojiId = ?',
        whereArgs: [emojiID]);
    return result.length;
  }

  // close db
  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}

Mood_Chart文件片段

    import 'package:flutter/material.dart';
    import 'dart:math';
    import 'package:charts_flutter/flutter.dart' as charts;
    import '../view/mood.dart';
    import '../models/mood_db.dart';
    import 'dart:async';

    class Mood {
      String _emoji;
      int _numOfDays; // this has to int bcz charts can't take future<int>
      charts.Color _color;

      Mood(this._emoji, this._numOfDays, this._color);
    }

    class MoodChart extends StatefulWidget {
      @override
      _MoodChartState createState() => _MoodChartState();
    }

    class _MoodChartState extends State<MoodChart> {
      DatabaseHelper _databaseHelper = DatabaseHelper();
      List<Mood> _data;
      List<charts.Series<Mood, String>> _chartData;

      // Here I used async-await but this function still return Future<int>    
      numOfDaysFn(int id) async {
        int numOfDays =await _databaseHelper.numOfMoodDays(id);
        return numOfDays;
      }

      void initData() async {
        _chartData = List<charts.Series<Mood, String>>();

        _data = <Mood>[
          Mood(
              allMoods[0], numOfDaysFn(1), charts.MaterialPalette.red.shadeDefault),
          Mood(allMoods[1], numOfDaysFn(2),
              charts.MaterialPalette.blue.shadeDefault),
          Mood(allMoods[2], numOfDaysFn(3),
              charts.MaterialPalette.gray.shadeDefault),
          Mood(allMoods[3], numOfDaysFn(4),
              charts.MaterialPalette.indigo.shadeDefault),
          Mood(allMoods[4], numOfDaysFn(5),
              charts.MaterialPalette.green.shadeDefault),
        ];
        _chartData.add(charts.Series(
          id: 'Mood',
          data: _data,
          colorFn: (Mood mood, _) => mood._color,
          domainFn: (Mood mood, _) => mood._emoji,
          measureFn: (Mood mood, _) => **mood._numOfDays**, //this can't take futures
        ));
      }

      @override
      void initState() {
        super.initState();
        initData();
      }

      @override
      Widget build(BuildContext context) {
        return Container(
          child: charts.PieChart(
            _chartData,
            animate: true,
          ),
        );
      }
    }
List allMoods = ['Disgusting', 'Bad', 'Ok', 'Good', 'Amazing'];

共有1个答案

蒲曦
2023-03-14

我不知道此代码是否运行,因为您的示例代码不完整。你需要学习飞镖期货是如何工作的。当您调用它时,结果将像Javascriptpromise的那样稍后返回

import 'package:flutter/material.dart';
import 'dart:math';
import 'package:charts_flutter/flutter.dart' as charts;
import '../view/mood.dart';
import '../models/mood_db.dart';
import 'dart:async';

class Mood {
  String _emoji;
  int _numOfDays; // this has to int bcz charts can't take future<int>
  charts.Color _color;

  Mood(this._emoji, this._numOfDays, this._color);
}

class MoodChart extends StatefulWidget {
  @override
  _MoodChartState createState() => _MoodChartState();
}

class _MoodChartState extends State<MoodChart> {
  DatabaseHelper _databaseHelper = DatabaseHelper();
  List<Mood> _data;
  List<charts.Series<Mood, String>> _chartData = null;

  // Here I used async-await but this function still return Future<int>    
  Future<List<int>> numOfDaysFn(List<int> days) async {
    return Future.wait(days.map((d) => _databaseHelper.numOfMoodDays(d)));
  }

  void initData( List<int> idx, List<int> days) {
    setState(() {


      _chartData = List<charts.Series<Mood, String>>();

      _data = <Mood>[
        Mood(
            allMoods[idx[0]-1], days[0], charts.MaterialPalette.red.shadeDefault),
        Mood(allMoods[idx[1]-1], days[1],
            charts.MaterialPalette.blue.shadeDefault),
        Mood(allMoods[idx[2]-1], days[2],
            charts.MaterialPalette.gray.shadeDefault),
        Mood(allMoods[idx[3]-1], days[3],
            charts.MaterialPalette.indigo.shadeDefault),
        Mood(allMoods[idx[4]-1], days[4],
            charts.MaterialPalette.green.shadeDefault),
      ];
      _chartData.add(charts.Series(
        id: 'Mood',
        data: _data,
        colorFn: (Mood mood, _) => mood._color,
        domainFn: (Mood mood, _) => mood._emoji,
        measureFn: (Mood mood, _) => mood._numOfDays, //this can't take futures
      ));
    });
  }

  @override
  void initState() {
    super.initState();
    var months = [1,2,3,4,5];
    numOfDaysFn(months).then((days) {
        initData(months, days);
    });
  }

  @override
  Widget build(BuildContext context) {
     if(_chartData != null ){
      return Container(
        child: charts.PieChart(
          _chartData,
          animate: true,
        ),
      );
    } else {
      return CircularProgressIndicator();
    }
  }
}

修订1

    import 'package:flutter/material.dart';
import 'dart:math';
import 'package:charts_flutter/flutter.dart' as charts;
import '../view/mood.dart';
import '../models/mood_db.dart';
import 'dart:async';

class Mood {
  String _emoji;
  int _numOfDays; // this has to int bcz charts can't take future<int>
  charts.Color _color;

  Mood(this._emoji, this._numOfDays, this._color);
}

class MoodChart extends StatefulWidget {
  @override
  _MoodChartState createState() => _MoodChartState();
}

class _MoodChartState extends State<MoodChart> {
  DatabaseHelper _databaseHelper = DatabaseHelper();
  List<Mood> _data;
  List<charts.Series<Mood, String>> _chartData = null;

  static List<charts.Color> DEFAULT_SHADE  = [
    null,
    charts.MaterialPalette.red.shadeDefault, 
    charts.MaterialPalette.blue.shadeDefault, 
    charts.MaterialPalette.gray.shadeDefault,
    charts.MaterialPalette.indigo.shadeDefault,
    charts.MaterialPalette.green.shadeDefault];

  Future<Mood> numOfDaysFn(int day) async {
    return Mood(  allMood[day-1] , _databaseHelper.numOfMoodDays(day), DEFAULT_SHADE[day] );
  }
  Future<List<Mood>> returnAllNumOfDaysFn( List<int> days) async {
    return Future.wait(days.map((d) => numOfDaysFn(d)));
  }

  @override
  void initState() {
    super.initState();
    var months = [1,2,3,4,5];
    returnAllNumOfDaysFn(months).then((moods) {
      var temp = charts.Series(
        id: 'Mood',
        data: _data,
        colorFn: (Mood mood, _) => mood._color,
        domainFn: (Mood mood, _) => mood._emoji,
        measureFn: (Mood mood, _) => mood._numOfDays, //this can't take futures
      );
      setState(() {
        _data = moods;
        _chartData = temp;
      });

    });
  }

  @override
  Widget build(BuildContext context) {
     if(_chartData != null ){
      return Container(
        child: charts.PieChart(
          _chartData,
          animate: true,
        ),
      );
    } else {
      return CircularProgressIndicator();
    }
  }
}

https://www.dartlang.org/guides/libraries/futures-错误处理

https://docs.flutter.io/flutter/widgets/state/setstate.html

颤振图为样品提供了静态数据。但是,您是动态地获取数据,因此需要调用set STATE。

 类似资料:
  • 问题内容: 我正在创建一种通过传递搜索字段从任何表中选择ID的方法。 但是我得到一个有关语法错误的MySqlException。当我查看“异常”消息时,它向我显示带引号的查询表!如何将表格作为不带引号的参数传递? 问题答案: 大多数数据库不允许您通过参数指定表名或列名。参数用于 值 。如果确实确实需要使它动态化,则应验证输入(它应该是一个已知的表名,并且该表中具有已知的列名),然后将其包括在SQL

  • 问题内容: 在我的RCP应用程序中,左侧有一个用于导航的视图,右侧有一个用于视图的文件夹。透视图看起来像这样: 我想根据用户在导航树中选择的内容打开不同的视图。认为这并不难。我的导航树视图: 这似乎很好。仅有一个小问题:我需要以某种方式将对象(例如,selectedItem)传递给我的视图,以使用户与其内容进行交互。我怎么做? 我看到了一些示例,其中一些同事编写了自己的视图,并将其放置在右侧。然后

  • 问题内容: 我已经熟悉Android框架和Java,并希望创建一个通用的“ NetworkHelper”类,该类可以处理大多数联网代码,使我能够从中调用网页。 我遵循了来自developer.android.com的这篇文章来创建我的网络类:http : //developer.android.com/training/basics/network- ops/connecting.html 码:

  • 问题内容: 我正在创建一个分页类,需要将两个参数传递给我的LIMIT子句的MySQL存储过程。 我将它们作为INT传递给我,并尝试这样的事情 但是,当我尝试保存该存储过程时,它给了我一个错误。有什么方法可以让我错过吗?还是我必须评估整个查询并执行它? 问题答案: 在5.5.6之前的版本中,无法在MySQL存储过程中进行参数化。您需要动态构建查询并执行它。 在5.5.6及更高版本中,只要将存储的pr

  • 问题内容: 我有以下内容,但它不起作用,我在stackoverflow上的某个地方读到了它的工作原理,但我似乎无法使其工作..它出错了……我在做错什么吗? 如果我确实传递了这样的数据-它可以工作-所以我知道我的服务正在工作 问题答案: 我相信代码将在对象上调用.value或.toString(),然后通过网络传递。您想传递JSON。 因此,包括JSON JavaScript库 http://www

  • 问题内容: 我有一个对象,其中包含多个通用键值道具,我想将它们传递给一些jsx。像这样: 我希望这可以作为传递单个道具的功能: 这可能吗? 问题答案: 这可能吗? 是的,为什么您认为不可能,但是发送方式不正确。 的含义是: 因此,如果您默认不指定任何值,它将采用。要传递对象,您需要这样编写: 更新: 如果您有一个对象,并且希望将所有属性作为单独的属性传递,则将其编写为: