Flutter: передача будущего<int> как int в чарты
Я делаю приложение для проверки настроения, используя флаттер, где пользователь выбирает один из 5 смайликов, чтобы рассказать о своем настроении. Я хочу отобразить круговую диаграмму с данными смайликов против числа дней, в течение которых он был выбран. Проблема в том, что мне нужно получить данные из базы данных sqflite, чтобы получить numOfDays. Выбран определенный эмодзи, который будет иметь тип Future, но диаграммы не могут принимать Futures, я пытался использовать 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
Фрагмент файла базы данных
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;
}
Фрагмент файла 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,
),
);
}
}
1 ответ
Я не знаю, работает ли этот код, потому что ваш пример кода не завершен. Вам нужно узнать, как работают дартс фьючерсы. Когда вы позвоните, результат вернется позже, как обещания Javascript
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;
// Change to return a Future with a list of results.
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) {
_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, //No longer a futures
));
}
@override
void initState() {
super.initState();
var months = [1,2,3,4,5];
//I do not think you should block initState. Use then.
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(); //Added a loading icon
}
}
}
https://www.dartlang.org/guides/libraries/futures-error-handling
https://docs.flutter.io/flutter/widgets/State/initState.html