Reputation: 71
I am a real newbie of flutter and would like to seek your help to solve the following problem:
I want to write the current time to a file but following error is shown:
======= Exception caught by widgets library =====================
The following NoSuchMethodError was thrown building Builder: The method 'writeStartTimeString' was called on null. Receiver: null Tried calling: writeStartTimeString("1629015208721")
Here is my code:
**startTimeStorage.dart**
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class StartTimeStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print('$path/startTime.txt');
return File('$path/startTime.txt');
}
Future<String> readStartTimeString() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
print('reading');
print(contents);
return contents;
} catch (e) {
// If encountering an error, return ''
return '';
}
}
Future<File> writeStartTimeString(String startTimeString) async {
final file = await _localFile;
print('writing');
print(startTimeString);
// Write the file
return file.writeAsString(startTimeString);
}
}
**main File:**
class ParkingTimerScreen extends StatefulWidget {
StartTimeStorage startTimeStorage;
_ParkingTimerScreen createState() => _ParkingTimerScreen();
}
class _ParkingTimerScreen extends State<ParkingTimerScreen> {
@override
void initState() {
super.initState();
var _timestamp = DateTime.now().millisecondsSinceEpoch;
print('printing _timestamp:$_timestamp');
//Writing to file, ***where error appears.***
widget.startTimeStorage.writeStartTimeString(_timestamp.toString());
//Reading from file and store the value to startTimeString
widget.startTimeStorage.readStartTimeString().then((String value) {
startTimeString = value;
});
//...other code.....
//.....
}
Upvotes: 0
Views: 166
Reputation: 2355
you should use an initializer
in your main file ParkingTimerScreen
widget get the startTimeStorage
but you did not initialize it and the application throws that error
because startTimeStorage
is null and readStartTimeString
call on a null variable
class ParkingTimerScreen extends StatefulWidget {
StartTimeStorage startTimeStorage;
ParkingTimerScreen({required this.startTimeStorage});
_ParkingTimerScreen createState() => _ParkingTimerScreen();
}
Upvotes: 0
Reputation: 318
You have to initialise the StartTimeStorage variable in ParkingTimeScreen Class.
class ParkingTimerScreen extends StatefulWidget {
StartTimeStorage startTimeStorage = StartTimeStorage();
_ParkingTimerScreen createState() => _ParkingTimerScreen();
}
Upvotes: 1