I found this answer about storing global configuration into globals.dart
.
How can I load configuration into it from assets/config.json
?
I've tried like this:
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 {
...
}
The application starts with a white screen. Nothing happens, no errors. I guess that await rootBundle.loadString(...)
causes the application to hang.
You can copy paste run full code below
You need to add WidgetsFlutterBinding.ensureInitialized()
in main()
without this line will produce white screen
globals.dart
Map<String, dynamic> config = {};
config.json
{
"id": "1",
"name": "abc"
}
code snippet
void main() async{
WidgetsFlutterBinding.ensureInitialized();
globals.config = jsonDecode(await rootBundle.loadString('assets/config.json'));
runApp(MyApp());
}
pubspec.yaml
assets:
- assets/
working demo
full code
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),
),
);
}
}