Флаттер, рассчитанный двойной не работают для круговой прогресс бар - PullRequest
0 голосов
/ 05 апреля 2020

Я хочу рассчитать процентное соотношение для различных круговых индикаторов с данными из моей базы данных Firestore. Но когда я использую вычисленные значения Double вместо жестко закодированных double, я получаю эту ошибку, и я не могу объяснить себя, почему я получаю эту ошибку в терминале: | Получатель 'weekActivity' был вызван как ноль. Получатель: null Пробный вызов: weekActivity | Может кто-нибудь помочь мне исправить эту ошибку?

Сообщение об ошибке

import 'dart:core';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_circular_chart/flutter_circular_chart.dart';
import 'package:testapp/models/Goals.dart';
import 'package:testapp/services/Services.dart';

class ReadingPage extends StatefulWidget {
final Goal goal;

const ReadingPage({Key key, this.goal}) : super(key: key);

@override
_ReadingPageState createState() => _ReadingPageState();
}

class _ReadingPageState extends State<ReadingPage> {

int _currentValue = 1;

//weeklyGoals
bool weekActivityFinished = false;
bool weekReadTimeFinished = false;

 @override
 Widget build(BuildContext context) {
 final _chartSize = const Size(145, 145);

 return Scaffold(
    resizeToAvoidBottomPadding: false,
    appBar: PreferredSize(
    preferredSize: Size.fromHeight(35),
child: AppBar(
title: Align(
alignment: Alignment.center,
child: Text('Reading', style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.grey[900],
fontSize: 25,
decoration: TextDecoration.underline,
decorationColor: Color(0XFF006699),
decorationThickness: 1.5,
),),
),
backgroundColor: Colors.white,
),
),
body: Container(
margin: EdgeInsets.symmetric(vertical: 0),
height: 260.0,
child: StreamBuilder(
stream: FirestoreService().getGoals(),
builder: (BuildContext context,
AsyncSnapshot<List<Goal>> snapshot) {
if (snapshot.hasError || !snapshot.hasData)
return Center(child: CircularProgressIndicator(
backgroundColor: Color(0XFF1954A1),
));
return SizedBox(
height: 250,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
Goal goal = snapshot.data[index];
return Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(
top: 5, bottom: 10, left: 30, right: 30),
child: Container(
width: 330.0,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(20.0)),boxShadow: [
BoxShadow(
color: Colors.grey[500],
offset: const Offset(0.5, 1),
blurRadius: 5.0,
spreadRadius: 0.1,
),
]),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 20),
width: 240,
child: Align(
alignment: Alignment.topLeft,
child: Container(
child: Text(
'WeeklyGoals', style: TextStyle(
fontSize: 25,
),),
),
),
),
Align(
alignment: Alignment.topRight,
child: Container(
padding: EdgeInsets.only(top: 5,right: 0, left: 0,
bottom: 0),
child: FlatButton(
child: Text('edit', style: TextStyle(
fontSize: 16,
color: Colors.yellow[700]
),),
onPressed: () {}
)
),
)
],
),
Row(
children: <Widget>[
Container(
width: 160,
margin: EdgeInsets.only(right: 10),
child: Column(
children: <Widget>[
Text('Activity', style: TextStyle(
fontSize: 18
),),
Center(
child: new AnimatedCircularChart(
size: _chartSize,
initialChartData: <
CircularStackEntry>[
new CircularStackEntry(
<CircularSegmentEntry>[
new CircularSegmentEntry(
_weekActivityProgress(),
weekActivityFinished
? Colors
    .yellow[700]
    : Color(
0XFF006699),
rankKey: 'completed',
),
new CircularSegmentEntry(
100,
Colors.grey[300],
rankKey: 'remaining',
),
],
rankKey: 'progress',
),
],
chartType: CircularChartType
    .Radial,
percentageValues: true,
holeLabel: '${goal
    .weekActivity != null
? goal.weekActivity
    : '-'}/${goal
    .weekActivityGoal != null
? goal.weekActivityGoal
    : '-'}',
labelStyle: new TextStyle(
color: Colors.blueGrey[600],
fontWeight: FontWeight.bold,
fontSize: 24.0,
),
),
),
],
),
),
Container(
width: 160,
child: Column(
children: <Widget>[
Text('Time', style: TextStyle(
fontSize: 18
),),
Center(
child: new AnimatedCircularChart(
size: _chartSize,
initialChartData: <
CircularStackEntry>[
new CircularStackEntry(
<CircularSegmentEntry>[
new CircularSegmentEntry(
_weekReadingProgress(),
weekReadTimeFinished
? Colors
    .yellow[700]
    : Color(
0XFF006699),
rankKey: 'completed',
),
new CircularSegmentEntry(
100,
Colors.grey[300],
rankKey: 'remaining',
),
],
rankKey: 'progress',
),
],
chartType: CircularChartType
    .Radial,
percentageValues: true,
holeLabel: '${goal
    .weekReadTime != null
? goal.weekReadTime
    .toStringAsFixed(2)
    : '-'} / ${goal
    .weekReadTimeGoal != null
? goal.weekReadTimeGoal
    : '-'}',
labelStyle: new TextStyle(
color: Colors.blueGrey[600],
fontWeight: FontWeight.bold,
fontSize: 24.0,
),
),
),
],
),
),
],
),
],
),
),
),
]);
}),
);
})));
}

//week
double _weekReadingProgress(){
var _weekReadingProgress = widget.goal.weekReadTime != null? widget.goal.weekReadTimeGoal : 0 *100 ~/ 
widget.goal.weekReadTimeGoal;
if(widget.goal.weekReadTime.toInt() >= widget.goal.weekReadTimeGoal){
setState(() {
weekReadTimeFinished = true;
});}
return _weekReadingProgress.toDouble();
}

double _weekActivityProgress(){
var _weekActivityProgress = widget.goal.weekActivity != null? widget.goal.weekActivity : 0 *100 ~/ 
widget.goal.weekActivityGoal;
if(widget.goal.weekActivity >= widget.goal.weekActivityGoal){
setState(() {
weekReadTimeFinished = true;
});}
return _weekActivityProgress.toDouble();
}}

1 Ответ

0 голосов
/ 05 апреля 2020

Переменная goal равна нулю в одном из мест, где вы используете goal.weekActivity.

Во всех местах, где вы используете goal.weekActivity, сначала убедитесь, что goal != null. Поскольку это происходит из Firestore, вполне возможно, что в базе данных нет целей, когда возникает эта ошибка. Если вы попробуете это и обнаружите, что оно всегда равно нулю, вы должны убедиться, что оно существует в базе данных.

...