Reputation: 67
I have a class named employee
with a propertie aStart
of type TimeofDay.
When I try to set the value of startWork
of an instance of employee it doesn't work. It's always null.
Funnily enough it works with all the other properties of employee. (types: String, DateTime, int) #
Below the code:
import 'package:flutter/material.dart';
class Employee {
TimeOfDay start;
TimeOfDay get getStart => this.start = start;
set setStart(TimeOfDay start) => this.start = start;
Employee(this.start);
}
import 'package:flutter/material.dart';
import 'package:testProjekt/employee.dart';
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
Employee employee;
FirstPage(this.employee);
}
class _FirstPageState extends State<FirstPage> {
TimeOfDay _time = TimeOfDay.now();
_selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
builder: (BuildContext context, Widget child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
child: child,
);
});
if (picked != null)
setState(() {
_time = picked;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
SizedBox(
height: 50,
),
Container(
child: ElevatedButton(
child: Text('selectTime'),
onPressed: () => _selectTime(context),
),
),
Text('selected Time:' + '$_time'),
Container(
child: ElevatedButton(
child: Text('saveTime'),
onPressed: () => {
widget.employee.setStart = _time,
print(widget.employee.getStart.toString())
}),
),
Text('SaveTimeofEmployee:'),
],
));
}
}
import 'package:flutter/material.dart';
import 'package:testProjekt/employee.dart';
import 'package:testProjekt/firstPage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Employee employee;
@override
Widget build(BuildContext context) {
return MaterialApp(home: FirstPage(employee));
}
}
Upvotes: 1
Views: 386
Reputation: 7553
Well, there are a couple of things wrong with your example.
Lots of typos, missing semicolons and wrong lambda syntax () => {}
. This may be caused by copying and adapting. So next time use some IDE/Dartpad/Codepen before you copy code so you can make sure it at least compiles.
You never construct an employee. MyApp.employee
is null
and is never assigned. This results in the FirstPage.employee
also being null
and thus causing your error.
Your setter/getter naming is not great. Read more here: https://dart.dev/guides/language/language-tour#getters-and-setters
I have corrected all the typos/errors and created a codepen that works. But it is not possible to exactly say what is wrong based on your sample code. https://codepen.io/kuhnroyal/pen/YzpYZPR
Upvotes: 2