【问题标题】:How do I load my local json into List<Map> variable?如何将本地 json 加载到 List<Map> 变量中?
【发布时间】:2019-04-11 21:01:57
【问题描述】:

如何将本地 json 加载到 List 变量中?

这是我的本地 json。

[
  {“id”: 00”, “name”: ”TRL”},
  {“id”: 01”, “name”: ”USD”},
  {“id”: 02”, “name”: ”GBP”},
  {“id”: 03”, “name”: ”EUR”},
]

但是这可行:

List<Map> _myCurrency = [
  {“id”: 00”, “name”: ”TRL”},
  {“id”: 01”, “name”: ”USD”},
  {“id”: 02”, “name”: ”GBP”},
  {“id”: 03”, “name”: ”EUR”},
];

我的问题是我将货币数据移动到 currency.json 文件中。我可以加载 json,但无法分配给 List 变量。有什么帮助吗?

更新:

String jsonTCBanks =
await rootBundle.loadString("packages/capi/currency.json");
List<Map> _myCurrency = json.decode(jsonTCBanks);

我收到错误;

type 'List<dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>'

如果我使用 Map _myCurrency json.decode 有效,但我失去了键值属性。

UPDATE-2: 我不断收到错误:

I/flutter (16273): The following assertion was thrown building MyHomePage(dirty, state: _MyHomePageState#44865):
I/flutter (16273): type 'MappedListIterable<Map<dynamic, dynamic>, DropdownMenuItem<dynamic>>' is not a subtype of type
I/flutter (16273): 'List<DropdownMenuItem<String>>'
    class _MyHomePageState extends State<MyHomePage> {
      String _mySelectedCurrency;
      List<Map> _myCurrencies;

      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        _loadLocalJsonData();
      }

      Future _loadLocalJsonData() async {
        String jsonCurrency = await rootBundle
            .loadString("packages/capi/currency.json");
        setState(() {
          _myCurrencies = List<Map>.from(jsonDecode(jsonCurrency) as List);
          print("*******_myCurrencies: $_myCurrencies");// This part works correctly
        }); 
      }

      @override
      Widget build(BuildContext context) {
        return _myCurrencies == null ? _buildWait(context) : _buildRun(context);
      }

  // TODO: BUILD RUN
  Widget _buildRun(BuildContext context) {
    final _itemsName = _myCurrencies.map((c) {
      return new DropdownMenuItem<String>(
        value: c["id"].toString(),
        child: new Text(c["name"].toString()),
      );
    }).toList();

    return new Scaffold(
        key: _scaffoldKey,
        body: new SafeArea(
            top: false,
            bottom: false,
            child: new Form(
                key: _formKey,
                child: new ListView(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 32.0),
                  children: <Widget>[
                    //TODO: CURRENCY ###########################################
                    new FormField<String>(
                      builder: (FormFieldState<String> state) {
                        return InputDecorator(
                          decoration: InputDecoration(
                            labelText: 'CHOOSE CURRENCY',
                            labelStyle: TextStyle(
                                fontSize: 18.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.green.shade700),
                            errorText: state.hasError ? state.errorText : null,
                          ),
                          isEmpty: _mySelectedCurrency == '',
                          child: new DropdownButtonHideUnderline(
                            child: new DropdownButton<String>(
                              style: TextStyle(
                                fontSize: 14.0,
                                color: Colors.black,
                                fontWeight: FontWeight.w500,
                              ),
                              value: _mySelectedCurrency,
                              isDense: true,
                              onChanged: (String newValue) {
                                setState(() {
                                  _mySelectedCurrency = newValue;
                                  state.didChange(newValue);
                                });
                              },
                              items: _itemsName,
                            ),
                          ),
                        );
                      },
                      validator: (val) {
                        return val != '' ? null : 'Choose Currency...';
                      },
                    ),
                  ],
                ))));
  }

      // TODO: BUILD WAIT
      Widget _buildWait(BuildContext context) {
        return new Scaffold(
          body: new Center(child: CircularProgressIndicator()),
        );
      }

    }

【问题讨论】:

    标签: json dart flutter


    【解决方案1】:

    您需要将其从字符串解码为数据结构,并通过创建具有所需类型的新列表来调整类型,并在其中传递从jsonDecode 返回的列表:

    import 'dart:convert';
    
    ...
    
    List<Map> _myCurrency = List<Map>.from(jsonDecode(json) as List);
    
    final currencyItems = _myCurrency.map(
        (c) => DropdownMenuItem<String>(c['id'], child: Text(c['name'])).toList();
    DropdownButton(items: currencyItems);     
    

    【讨论】:

    • 我更新了我的问题。我收到错误:类型'List'不是'List>'类型的子类型
    • 感谢 Günter 的工作。最后一个问题。如何将 List _myCurrency 添加到下拉按钮中?
    • 我会试试谢谢,如果不行我会打开新问题
    • 没有工作,因为我不断收到同样的错误。我更新了我的问题。
    • return new DropdownMenuItem&lt;dynamic&gt;( value: c["id"].toString(),更改为return new DropdownMenuItem&lt;String&gt;( value: c["id"].toString(),
    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2020-09-23
    • 2011-11-30
    • 2022-01-21
    • 2021-04-07
    相关资源
    最近更新 更多