Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: get default context? or load assets without context?

Tags:

flutter

I'm trying to load a json file in a class extending SearchDelegate to search through its content.

I have a method to load this file:

Future<void> loadCountryData() async {
    try {
      String data = await DefaultAssetBundle
          .of(context)
          .loadString("assets/data/countries.json");
      _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}

Unfortunately this requires a Buildcontext (context) that seems only to be available in the SearchDelegate build methods (like buildActions, buildLeadings, etc), but no outside like for example in the constructor.

https://docs.flutter.io/flutter/material/SearchDelegate-class.html

As the @override xy build methods in SearchDelegate are called with every change in the search field, I would load my file over and over again, which is of course not ideal. I want to load my file once at the beginning only.

Is there a way to get some sort of get default context that I could use for example in the constructor of SearchDelegate. Like in android (if I remmeber correctly)?

Or can I load an assets file without .of(context)?

like image 457
Chris Avatar asked Aug 27 '26 00:08

Chris


1 Answers

There is an option to get builtin AssetBundle without specifying a reference to BuildContext. Here is an example of how it could be done:

import 'package:flutter/services.dart'; // is required

Future<void> loadCountryData() async {
    try {
        // we can access builtin asset bundle with rootBundle
        final data = await rootBundle.loadString("assets/data/countries.json");
        _countries = json.decode(data);
    } catch (e) {
      print(e);
    }
}
like image 146
ChessMax Avatar answered Aug 28 '26 15:08

ChessMax