从main()调用await rootBundle.loadString(…)时,Flutter应用程序挂起
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从main()调用await rootBundle.loadString(…)时,Flutter应用程序挂起相关的知识,希望对你有一定的参考价值。
我发现this answer关于将全局配置存储到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(...)
导致应用程序挂起。
答案
您可以在下面复制粘贴运行完整代码您需要在WidgetsFlutterBinding.ensureInitialized()
中添加main()
没有这条线会产生白屏
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),
),
);
以上是关于从main()调用await rootBundle.loadString(…)时,Flutter应用程序挂起的主要内容,如果未能解决你的问题,请参考以下文章