如何在主方法Flutter中加载json



我正试图将一个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());
}

使用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(),
),
);
});
}
}

我似乎不是,而是尝试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(),
),
);
}
}

最新更新