【问题标题】:LOAD LOCAL JSON FILE USING FUTURE BUILDER使用 FUTURE BUILDER 加载本地 JSON 文件
【发布时间】:2021-10-31 13:30:12
【问题描述】:

为什么仍然没有显示数据。尝试了许多格式。但它仍然显示错误页面。我遵循我在 youtube 和本组中观看和阅读的所有程序。但我仍然无法加载 json 文件

class _PlantPageState extends State<PlantPage> {
  
    List<Plants> planty = [];
  Future getPlantsLocally() async {
    final assetBundle = DefaultAssetBundle.of(context);
    final data = await assetBundle.loadString('assets/plants.json');
    final body =  await json.decode(data);

    var list = body["plant"] as List<dynamic>;
    setState(() {
      planty = list.map((e) => Plants.fromJson(e)).toList(); 
    });
  }


  @override
  Widget build(BuildContext context) => Scaffold(
    body: FutureBuilder(
      future: getPlantsLocally(),
      builder:(context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          default:
          if (planty.length > 0) {
            return Container(
              height: 200,
              child: ListView.builder(
                itemCount: planty.length,
                itemBuilder: (BuildContext context, index) {
                  return Card(
                    margin: EdgeInsets.all(15.0),
                    color: Colors.green[600],
                    child: ListTile(
                      title: Text(planty[index].name?? 'name',),
                    ),
                  );
                }
                ),
            );
          }
          else {
            return Center(child: Text('Error Error'),);
          }
        }

这是我的数据库示例。我已经使用数据类生成器对其进行了解析。难道我的数据库不对?还是我的抓取文件?

{
  "plant":
 [
        {
            "id": "1",
            "name": "ALOCASIA-ELEPHANT EARS",
            "image": "assets/images/ALOCASIA.jpeg",
            "descript": "Alocasia plant (Alocasia mortfontanensis) is a hybrid species between Alocasia longiloba and Alocasia sanderiana. The Alocasia is known for its large leaves and wide variety of cultivars within the species. Alocasia plant is native to tropical Asia and Australia.",
            "charac": [{
              "planttype": "Herb",
              "lifespan": "Perennial",
              "bloomtime": "Spring, summer",
              "plantheight": "1-2 feet",
              "spread": "7 feet",
              "leafColor": "PurpleGreenGreySilver"
            }
            ],
            "scienclass": [
                {
                "genus": "Alocasia - Elephant's-ears, Taro, Kris plant",
                "family": " Araceae - Arum, Aroids ",
                "order": "Alismatales - Water plantains and allies",
                "classes": "Liliopsida - Monocotyledons, Monocots ",
                "phylum":"Tracheophyta - Vascular plants, Seed plants, Ferns, Tracheophytes"
            }
            ],
            "pestdesease": " Stem rot, crown rot, root rot, leaf spot, mealy bugs, aphids",
            "requirements":[{
                "difficultyrating": "Alocasia plant is super easy to take care of, with resistance to almost all pests and diseases. It is a perfect option for gardeners with brown thumbs.",
                "sunlight": "Full shade to partial sun",
                "hardenesszone": " 9-11 ",
                "soil": "Loose, fertile and well-drained humus soil"
            }
         ],
            "careguide":[
                {
                "water": "Moisture-loving, keep the soil moist but do not let water accumulate.",
                "fertilizaton": "Fertilization once in spring. ", 
                "pruning": "Fertilization once in spring. ", 
                "plantingtime": "Spring, summer, autumn ",
                "propagation": "Division ",
                "pottingsuggestion": " Needs excellent drainage in pots."
            }
            ],
            "toxictohuman": "Is the alosdadadsadadsa",
        },

你们认为这个流程的错误是什么?

【问题讨论】:

    标签: json database flutter local


    【解决方案1】:

    您需要更改您的getPlantsLocally() 以返回一个列表,futurBuilder 应该使用getPlantsLocally() 返回的列表而不是局部变量planty。希望这行得通。

    class _PlantPageState extends State<PlantPage> {
      
      Future<List> getPlantsLocally() async {
        final assetBundle = DefaultAssetBundle.of(context);
        final data = await assetBundle.loadString('assets/plants.json');
        final body =  await json.decode(data);
    
        var list = body["plant"] as List<dynamic>;
        var planty = list.map((e) => Plants.fromJson(e)).toList(); 
        return planty;
      }
    
    
      @override
      Widget build(BuildContext context) => Scaffold(
        body: FutureBuilder(
          future: getPlantsLocally(),
          builder:(context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
                return Center(child: CircularProgressIndicator());
              default:
              if (snapshot.hasData && snapshot.data!.length > 0) {
                return Container(
                  height: 200,
                  child: ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (BuildContext context, index) {
                      return Card(
                        margin: EdgeInsets.all(15.0),
                        color: Colors.green[600],
                        child: ListTile(
                          title: Text(snapshot.data[index].name?? 'name',),
                        ),
                      );
                    }
                    ),
                );
              }
              else {
                return Center(child: Text('Error Error'),);
              }
            }
    

    【讨论】:

    • 你好。我试过你的想法。快照.数据![索引].名称。是为标题。但是当我运行系统时。它显示 Else 这是错误错误
    【解决方案2】:
    class PlantsApi {
      static Future<List<Plant>> getPlantsLocally(BuildContext context) async {
         final assetBundle = DefaultAssetBundle.of(context);
        final data = await assetBundle.loadString('assets/plants.json');
        final body =  await json.decode(data);
        var list = body["plant"] as List<dynamic>;
        var planty = list.map((e) => Plant.fromMap(e)).toList();
        return planty;
      }
    }
    

    获取数据是问题所在。谢谢你。我删除 List Plant = []

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2014-11-24
      • 2012-09-12
      • 2012-05-16
      相关资源
      最近更新 更多