从 main() 调用 await rootBundle.loadString(...) 时,Flutter 应用程序挂起

Flutter application hangs when calling await rootBundle.loadString(...) from main()

我发现 将全局配置存储到 globals.dart

如何从 assets/config.json 加载配置?

我试过这样:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'globals.dart' as globals;

void main() async {
  globals.config = jsonDecode(await rootBundle.loadString('assets/config.json'));
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  ...
}

应用程序以白屏启动。什么都没有发生,没有错误。我猜 await rootBundle.loadString(...) 导致应用程序挂起。

您可以复制粘贴运行下面的完整代码
您需要在 main()
中添加 WidgetsFlutterBinding.ensureInitialized() 没有这一行会产生白屏

globals.dart

Map<String, dynamic> config = {};

config.json

{    
    "id": "1",
    "name": "abc"
}

代码片段

void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      globals.config = jsonDecode(await rootBundle.loadString('assets/config.json'));
      runApp(MyApp());
    }

pubspec.yaml

assets:
  - assets/

工作演示

完整代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'globals.dart' as globals;

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  globals.config = jsonDecode(await rootBundle.loadString('assets/config.json'));
  runApp(MyApp());
}

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(        
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Scaffold(
      appBar: AppBar(        
        title: Text(widget.title),
      ),
      body: Center(        
        child: Column(         
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(globals.config["id"]),
            Text(globals.config["name"]),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), 
    );
  }
}