如何在主方法Flutter中加载json?

How to load json in main method Flutter?

我正在尝试将 json 文件加载到我的 main() 应用程序方法中。 你能告诉我这是否可能吗?我尝试了 File 和 rootBundle,但似乎 Assets 文件夹还没有准备好。

这是我的代码:

资产

  assets:
    - assets/settings/settings.json

主要方法

void main() async {
    final file = await rootBundle.loadString('assets/settings/settings.json');
      final data = jsonDecode(file);
      Settings settings = Get.put(Settings.fromJson(data), permanent: true);
  runApp(MyApp());
}

我好像不是,而是尝试 MyApp 并使其成为 statefullWidget


class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _load();
  }

  _load() async {
    final file = await rootBundle.loadString('assets/j.json');
    final data = await jsonDecode(file);
    print(data.toString());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: AppBarTheme(
          titleTextStyle: Theme.of(context).textTheme.headline1,
        ),
      ),
      home: Scaffold(
        body: Text("Body"),

        // MaxWidthButton(),
      ),
    );
  }
}

使用 FutureBuilder 找到解决方案

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  _load() async {
    final file = await rootBundle.loadString('assets/j.json');
    final data = await jsonDecode(file);
    print(data.toString());
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _load(),
        builder: (_, AsyncSnapshot<dynamic> snapshot) {
          return !snapshot.hasData
              ? Container(
                  color: Colors.white,
                  child: Center(
                      child: Container(
                    child: CircularProgressIndicator(),
                    width: 20,
                    height: 20,
                  )),
                )
              : MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: AppBarTheme(
          titleTextStyle: Theme.of(context).textTheme.headline1,
        ),
      ),
      home: Scaffold(
        body: Text("Body"),

        // MaxWidthButton(),
      ),
    );
        });
  }
}