dart 如何在Flutter中访问嵌套JSON文件中的特定数据?

suzh9iv8  于 5个月前  发布在  Flutter
关注(0)|答案(1)|浏览(89)

我有一个嵌套的json文件,结构如下(见图):
enter image description here
问题是我如何访问nutrition中的name值,以便输出例如:Protein?
通过下面的代码,我已经可以访问foodClass和description值,但不知道如何访问嵌套的值。

import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/services.dart';

class HomeScreen2 extends StatefulWidget {
  const HomeScreen2({Key? key}) : super(key: key);

  @override
  State<HomeScreen2> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen2> {
  List _items = [];

// Fetch content from the json file
  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/database.json');
    final data = await json.decode(response);
    setState(() {
      _items = data["SRLegacyFoods"];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Database',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: readJson,
              child: const Text('Load Data'),
            ),

            // Display the data loaded from database.json
            _items.isNotEmpty
                ? Expanded(
                    child: ListView.builder(
                      itemCount: 3,
                      itemBuilder: (context, index) {
                        return Card(
                          margin: const EdgeInsets.all(10),
                          child: ListTile(
                            leading: Text(_items[index]['foodClass']),
                            title: Text(_items[index]['description']),
                        //    subtitle: Text(_items[index]["description"]),
                          ),
                        );
                      },
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }
}

字符串
我试图访问:

_items[index]['foodNutrients']['nutrient']['name'];


但这不管用

1dkrff03

1dkrff031#

for(Map<String,dynamic> foodNutrient in _items[index]['foodNutrients']){
   print(foodNutrient['nutrient']['name']);
}

字符串

相关问题