#flutter #dart #input #formatexception
Вопрос:
я создаю приложение для таймера. домашняя страница будет страницей настроек. затем на странице настроек я создам кнопку и перейду на страницу inputdatacountdown. эта страница в основном является номером импорта пользователем. затем данные будут перенесены на страницу обратного отсчета. будет продолжительность, и я пройду к ней. проблема здесь в том, что я не знаю, почему flutter сообщает мне исключение формата. это ошибка, которую я получил
The following FormatException was thrown building Builder(dirty):
FormatException
The relevant error-causing widget was:
MaterialApp file:///C:/Users/gary gan/AndroidStudioProjects/myfirstflipclock_createown/lib/main.dart:11:5
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49 throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 178:5 parse
packages/myfirstflipclock_createown/settingpage.dart 39:63 <fn>
packages/flutter/src/material/page.dart 53:55 buildContent
packages/flutter/src/material/page.dart 106:27 buildPage
...
====================================================================================================
это мой код страницы настройки
class Settingpage extends StatelessWidget {
@override
//search for how to use if else in flutter by giving the terms
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('settingscreen'),
),
body: Container(
child: Column(children: [
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('go back home')),
SizedBox(height: 10.0,),
Expanded(
child: ListView(
padding: const EdgeInsets.all(8.0),
children: [
ElevatedButton(
onPressed: () {Navigator.push(
context,
MaterialPageRoute(builder: (context) => DateTimePicker()),
);
},
child: Text('set your time and date'),
),
SizedBox(height: 24.0,),
ElevatedButton(
onPressed: () {Navigator.push(
context,
MaterialPageRoute(builder: (context) => inputdatacountdown()),
);
},
child: Text('count down timer'),
),
SizedBox(height: 24.0,),
],
),
),
])),
);
}
}
это мой inputdatapage, а также страница обратного отсчета времени
class inputdatacountdown extends StatefulWidget {
var hourController = TextEditingController();
int inputdata;
inputdatacountdown(){
inputdata=int.parse(hourController.text);
}
@override
_inputdatacountdownState createState() => _inputdatacountdownState();
}
class _inputdatacountdownState extends State<inputdatacountdown> {
int inputdata;
_inputdatacountdownState(){
inputdata=int.parse(hourController.text);
}
var hourController = TextEditingController();
final minuteController = TextEditingController();
final secondController = TextEditingController();
final _key = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
final nametext =
MediaQuery.of(context).platformBrightness == Brightness.dark
? Colors.white
: Colors.black;
final nametextonbutton =
MediaQuery.of(context).platformBrightness == Brightness.dark
? Colors.black
: Colors.white;
return Scaffold(
body: Center(
child: Container(
child: Form(
key: _key,
child: Column(
children: [
TextFormField(
controller: hourController,
decoration: InputDecoration(
hintText: 'e.g 1',
labelText: 'hours',
border:
OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: () =>
hourController
.clear(),
),
),
keyboardType:
TextInputType.number,
textInputAction:
TextInputAction.done,
validator: (value) {
if (value.isEmpty) {
return 'hours cannot be empty';
} else
return null;
}),
TextFormField(
controller: minuteController,
decoration: InputDecoration(
hintText: 'e.g 1',
labelText: 'minutes',
border:
OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: () =>
minuteController
.clear(),
),
),
keyboardType:
TextInputType.number,
textInputAction:
TextInputAction.done,
validator: (value) {
if (value.isEmpty) {
return 'minutes cannot be empty';
} else
return null;
}),
TextFormField(
controller: secondController,
decoration: InputDecoration(
hintText: 'e.g 1',
labelText: 'second',
border:
OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: () =>
secondController
.clear(),
),
),
keyboardType:
TextInputType.number,
textInputAction:
TextInputAction.done,
validator: (value) {
if (value.isEmpty) {
return 'second cannot be empty';
} else
return null;
}),
FlatButton(
color: nametext,
onPressed: () {
if (_key.currentState
.validate()) {
print(
'hour: ${hourController.text}');
print(
'minutes: ${minuteController.text}');
print(
'second: ${secondController.text}');
_sumbitok();
Navigator.of(context).push(MaterialPageRoute(builder: (context)=>CountDownTimer( inputdataint: inputdata)));
}
},
child: Text(
'submit ',
style: TextStyle(
color:
nametextonbutton),
))
],
)),
),
),
);
}
void _sumbitok() {
Widget okbutton = FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('ok'),
);
AlertDialog alert = AlertDialog(
title: Text('Dialog title'),
content: Text("you have already submit the number"),
actions: [
okbutton,
],
);
showDialog(
context: context,
builder: (context) {
return alert;
},
);
}
}
class CountDownTimer extends StatefulWidget {
int inputdataint;
CountDownTimer({Key key,@required this.inputdataint}):super(key:key);
@override
_CountDownTimerState createState() => _CountDownTimerState();//inputdataint:
}
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
int inputdataint;
_CountDownTimerState({this.inputdataint});
AnimationController controller;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: Duration(seconds: inputdataint),//come back to you later
);
}
@override
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
final nametext =
MediaQuery.of(context).platformBrightness == Brightness.dark
? Colors.white
: Colors.black;
final nametextonbutton =
MediaQuery.of(context).platformBrightness == Brightness.dark
? Colors.black
: Colors.white;
return Scaffold(
backgroundColor: Colors.white10,
body: AnimatedBuilder(
animation: controller,
builder: (context, child) {
return Stack(children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Align(
alignment: FractionalOffset.center,
child: AspectRatio(
aspectRatio: 1.0,
child: Stack(
children: <Widget>[
Positioned.fill(
child: CustomPaint(
painter: CustomTimerPainter(
animation: controller,
backgroundColor: Colors.white,
color: themeData.indicatorColor,
)),
),
Align(
alignment: FractionalOffset.center,
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
crossAxisAlignment:
CrossAxisAlignment.center,
children: <Widget>[
Text(
"Count Down Timer",
style: TextStyle(
fontSize: 20.0, color: nametext),
),
Text(
timerString,
style: TextStyle(
fontSize: 112.0, color: nametext),
),
],
),
),
],
),
),
),
),
AnimatedBuilder(
animation: controller,
builder: (context, child) {
return FloatingActionButton.extended(
onPressed: () {
if (controller.isAnimating)
controller.stop();
else {
controller.reverse(
from: controller.value == 0.0
? 1.0
: controller.value);
}
},
icon: Icon(controller.isAnimating
? Icons.pause
: Icons.play_arrow),
label: Text(
controller.isAnimating ? "Pause" : "Play"));
}),
],
))
]);
}),
);
}
}
спасибо вам за ваше время и за вашу помощь.
Комментарии:
1. Ошибка возникает из
main.dart
-за того , не могли бы вы добавить код этого файла?
Ответ №1:
В следующем коде вы определяете hourController, текст которого по умолчанию пуст, а затем в конструкторе вы анализируете/преобразуете это пустое значение в int, что является причиной вашей проблемы. И ты тоже делал это на уроках государственного языка.
var hourController = TextEditingController();
int inputdata;
inputdatacountdown(){
inputdata=int.parse(hourController.text);
}
Чтобы решить эту проблему, вы можете задать значение по умолчанию для hourController
например
var hourController = TextEditingController(text: '1');