skip to Main Content

While app is loading I’m trying to load some json:

final contentJson = await rootBundle.loadString('assets/content.json');

But app loading stucks and white screen is displaying. No errors appear in the console.

Here my pubspec.yaml:

flutter:
  generate: true
  uses-material-design: true
  assets:
    - assets/icons/
    - assets/images/
    - assets/fonts/
    - assets/content.json

I have a guess that this is related to the web application. Because this doesn’t happen on other platforms.

Here full code surrounding invocation:

home_data_provider.dart

@override
  Future<List<ArticleDto>> getArticleDtos() async {
    final contentJson = await rootBundle.loadString('assets/content.json');
    final content = json.decode(contentJson) as Iterable<Map<String, dynamic>>;

    return List<ArticleDto>.from(
      content.map((articleData) async {
        final articlePath = articleData['articlePath'] as String;
        final article = await rootBundle.loadString(articlePath);

        return ArticleDto(
          title: articleData['title'] as String,
          topic: articleData['topic'] as String,
          articleInMarkdown: article,
          imagePath: articleData['imagePath'] as String,
          createdAt: articleData['createdAt'] as String,
        );
      }),
    );
  } 

home_repository.dart

@override
  Future<List<ArticleEntity>> getArticles() async {
    final articleDtos = await _dataProvider.getArticleDtos();
    return _articlesConverter.convertMultiple(articleDtos).toList();
  }

home_page.dart

Scaffold(
      body: BlocProvider(
        create: createHomeCubit,
        child: SomeChild()),
    );

create_home_cubit.dart

HomeCubit createHomeCubit(BuildContext context) {
  final localeService = context.read<ILocaleService>();
  return HomeCubit(
    context.read<IThemeService>(),
    context.read<ILocaleService>(),
    HomeRepository(
      articlesConverter: ArticlesConverter(),
      dataProvider: HomeDataProvider(localeService.currentLocale.languageCode),
    ),
  );
}

getArticles will be called inside cubit constructor.

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution to my problem here

    I'm starting to think that the problem is due to the fact that the method rootBundle.loadString call occurs during the execution of the build method. I don't fully understand why this is a problem, but it helped.


  2. Here is the expected answer:

    import 'package:flutter/services.dart' show rootBundle;
    
    Future<Map<String, dynamic>> loadJsonData() async {
    // Load the JSON file using rootBundle
    String jsonString = await rootBundle.loadString('assets/content.json');
    
    // Parse the JSON string
    Map<String, dynamic> jsonData = json.decode(jsonString);
    
    return jsonData;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search