简体   繁体   English

¿ 如何读取 flutter 中的本地 json 文件?

[英]¿How to read local json files in flutter?

I've read many posts where someone explains how to do it, but in my case, it's not working and I'm not sure why, I've added the right folder to the pubspec.yaml and everything, this is my code我读过很多帖子,有人解释了如何做,但就我而言,它不起作用,我不知道为什么,我已将正确的文件夹添加到 pubspec.yaml 和所有内容,这是我的代码

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';
import 'package:workout_time/Widgets/routines_widget.dart';

void main() => runApp(WorkoutTime());

class WorkoutTime extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Great App',
      home: Scaffold(
        body: RoutinesWidget(),
      ),
    );
  }
}

class RoutinesWidget extends StatefulWidget {
  @override
  _RoutinesWidgetState createState() => _RoutinesWidgetState();
}

class _RoutinesWidgetState extends State<RoutinesWidget> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: FutureBuilder(
        future: rootBundle.loadString("assets/data.json"),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgressIndicator();
          }
          var myData = jsonDecode(snapshot.data.toString());
          return Center(
            child: Text(myData == null ? "Nothing here" : myData),
          );
        },
      ),
    );
  }
}

when I run it, I get the CircularProgressIndicator widget, meaning that the snapshot has no data.当我运行它时,我得到了 CircularProgressIndicator 小部件,这意味着快照没有数据。 Can anyone help me?谁能帮我?

Edit: here is the part in the pubspec.yaml where I import the folder:编辑:这是 pubspec.yaml 中我导入文件夹的部分:

assets:
  - assets/
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

Code - pubspec.yaml代码 - pubspec.yaml

assets: - assets/json/资产:-资产/json/

Code - In a Class代码 - 在 Class

   static Map<dynamic, dynamic> jsonData;
    loadJson() async {
      String jsonContent = await rootBundle.loadString("assets/json/data.json");
      jsonData = json.decode(jsonContent);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM