JSON File not being found even when being being declared properly

38 views Asked by At

I"m trying to create a calendar api that grabs the events from a week ahead and displays them in advance. The googleCalendarAPi.json contains the data for the service account that grabs the data from the calendar.

Future<void> initializeCalendarApi() async {
  // Adjust the path according to where you placed the file
  final file = File('assets/googleCalendarAPI.json'); 
  final jsonString = await file.readAsString();
  final jsonMap = json.decode(jsonString) as Map<String, dynamic>;

  final credentials = auth.ServiceAccountCredentials.fromJson(jsonMap);
final client = await auth.clientViaServiceAccount(credentials, _scopes);
  _calendarApi = calendar.CalendarApi(client);
}

  Future<List<calendar.Event>> fetchWeekEvents(DateTime startDate) async {
  await initializeCalendarApi();

  final calendarId = '(imagine a calendar id here)';
  final startTime = startDate.subtract(Duration(days: startDate.weekday - 1));
  final endTime = startTime.add(Duration(days: 7));

  try {
    var events = await _calendarApi.events.list(
      calendarId,
      timeMin: startTime.toUtc(),
      timeMax: endTime.toUtc(),
      singleEvents: true,
      orderBy: 'startTime',
    );

    return events.items ?? []; // Return an empty list if events.items is null
  } catch (e) {
    // Handle the error appropriately
    print('Error fetching events: $e');
    return []; // Return an empty list in case of an error
  }
}

The code doesn't return any errors immediately however whenever initializeCalendarApi() is called it gives me the error flutter: Error fetching events: PathNotFoundException: Cannot open file, path = 'assets/googleCalendarAPI.json' (OS Error: No such file or directory, errno = 2)

I've tried moving the file into different places and making sure that it was defined within pubspec.yaml

assets:
    - assets/googleCalendarAPI.json

however i'm still getting the error. If more information is needed to fix this problem please tell me.

2

There are 2 answers

0
Dewa Prabawa On BEST ANSWER

You could replace :

final file = File('assets/googleCalendarAPI.json'); 
final jsonString = await file.readAsString();

to

import 'package:flutter/services.dart' show rootBundle;

final jsonString = await rootBundle.loadString('assets/googleCalendarAPI.json');
final jsonMap = json.decode(jsonString) as Map<String, dynamic>;*
0
聂超群 On

Try replacing

final file = File('assets/googleCalendarAPI.json'); 
final jsonString = await file.readAsString();

with

final jsonString = rootBundle.loadString('assets/googleCalendarAPI.json');

Do not forget to import rootBundle:

import 'package:flutter/services.dart' show rootBundle;

Check loading assets for more info.