flutter读取项目中的json文件数据

前言

网上有很多读取的,但对于小白的我来说(刚接触flutter一周,dart完全不懂),从项目中读取 xxx.json文件,并将文件中的json内容转换为string对象是困难的,话不多说直接上代码

环境准备

由于我是在自己项目中实现的,有环境,及依赖需要引入,就全部都贴出来

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

以下是yaml文件的依赖引入

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.4.12
  camera: ^0.2.9+1
  video_player: ^0.5.2
  path_provider: ^0.4.1
  local_auth: ^0.3.0
  flutter_screenutil: ^0.4.2

项目中需要存在的json文件,data/currency.json;并且需要在yaml中注册

[
  {"ccy":"01","swccy":"TWD","chname":"新台币"},
  {"ccy":"02","swccy":"CYN","chname":"人民币"},
  {"ccy":"14","swccy":"USD","chname":"美元"}
]
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
      - data/currencies.json
      - data/accountTypy.json
      - data/currency.json

直接上代码

import 'dart:async';
import 'dart:convert';
import 'dart:io';


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/**
 * @Author:xcl_pccw
 * @Date: 2019-1-5
 */

class VB_POC_2_2_CreateAccount_Input extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new VB_POC_2_2_CreateAccount_Input_state();
  }
}

class VB_POC_2_2_CreateAccount_Input_state
    extends State<VB_POC_2_2_CreateAccount_Input> {
  List<dynamic> data;




  @override
  void initState() {
       Future<String> loadString = DefaultAssetBundle.of(context).loadString("data/currency.json");

       loadString.then((String value){
      // 通知框架此对象的内部状态已更改
      setState((){
        // 将参数赋予存储点击数的变量
        data = json.decode(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    //设计手稿与屏幕尺寸适配
    ScreenUtil.instance = ScreenUtil(width: 375, height: 736)..init(context);
    return new Scaffold(
      body: new ListView(
        children: <Widget>[
          character_2_4(context),
          cardInput_2_4(context),
        ],
      ),


      bottomNavigationBar: buttonSection_2_4(context), //4.底部按钮
    );
  }



//2.中部文字显示
  Padding character_2_4(BuildContext context) {
    return new Padding(
      padding: EdgeInsets.only(
          top: ScreenUtil().setWidth(30),
          left: ScreenUtil().setWidth(57),
          right: ScreenUtil().setWidth(57)), //距离布局调试
      child: new Container(
        child: new Padding(
          padding: EdgeInsets.only(top: ScreenUtil().setWidth(0)),
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.only(top: 0.0),
                child: new Text(
                  'Here’s what you need to',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(24),
                    color: Color.fromARGB(254, 86, 92, 100),
                  ),
                ),
              ),
              new Padding(
                padding: EdgeInsets.only(top: ScreenUtil().setWidth(8)),
                child: new Text(
                  'Open a new account',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(24),
                    color: Color.fromARGB(254, 64, 178, 230),
                  ),
                ),
              ),
            ],
          ),
        ),
        height: ScreenUtil().setWidth(67),
      ),
    );
  }

  final TextEditingController _controller_accountType =
      new TextEditingController.fromValue(
          new TextEditingValue(text: "_controller_accountType"));
  final TextEditingController _controller_currency =
      new TextEditingController.fromValue(
          new TextEditingValue(text: "_controller_currency"));
  final TextEditingController _controller_password =
      new TextEditingController.fromValue(
          new TextEditingValue(text: "_controller_password"));
  final TextEditingController _controller_remark =
      new TextEditingController.fromValue(
          new TextEditingValue(text: "_controller_remark"));

//3.中部输入框
  Padding cardInput_2_4(BuildContext context) {
    return new Padding(
      padding: EdgeInsets.only(
        top: ScreenUtil().setWidth(20),
        left: ScreenUtil().setWidth(20),
        right: ScreenUtil().setWidth(20),
      ),
      child: new Container(
        //卡片效果展示
        child: Card(
          child: new Padding(
            padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 15.0),
            child: new ListView(
              children: <Widget>[
                selectTrade(context, 'Account Type', selectValue_accountType),
                selectTrade(context, 'Currency', selectValue_currency),
                inputTrade(context, 'Password', _controller_password),
                inputTrade(context, 'Remark', _controller_remark),
              ],
            ),
          ),
        ),
        height: ScreenUtil().setWidth(369),
        width: ScreenUtil().setWidth(335),
      ),
      //第四层按钮显示
    );
  }

  var selectValue_accountType = '防不胜防的吧';
  var selectValue_currency = '防的就是你';

  Column selectTrade(
      BuildContext context, String TradeName, String selectValue) {
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        new Container(
          child: new Text(TradeName),
          margin: EdgeInsets.only(top: ScreenUtil().setWidth(15)),
          height: ScreenUtil().setWidth(18),
        ),
        new Container(
          decoration: BoxDecoration(
            border:
                Border(bottom: BorderSide(color: Colors.black54, width: 1.0)),
          ),
          width: ScreenUtil().setWidth(295),
          height: ScreenUtil().setWidth(48),
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new Container(
                child: new Text(selectValue),
                width: ScreenUtil().setWidth(235),
              ),
              new Container(
                margin: EdgeInsets.only(right: 0.0),
                child: PopupMenuButton(
                  itemBuilder: (BuildContext context){
                    List<PopupMenuItem<String>> list = new List<PopupMenuItem<String>>();

                    data.forEach((value){
                      PopupMenuItem<String> popupMenuItem = new PopupMenuItem(
                          value: value["swccy"], child: new Text(value["chname"]));
                      list.add(popupMenuItem);
                    });
                    return list;
                  },
                  icon: Icon(
                    Icons.keyboard_arrow_down,
                    color: Colors.blue,
                    size: ScreenUtil().setWidth(27),
                  ),
                  onSelected: (String result) {
                    setState(() {
                      print(result);
                      if(TradeName == 'Account Type'){
                        selectValue_accountType = result;
                      };
                      if(TradeName == 'Currency'){
                        selectValue_currency = result;
                      }
                    });
                    print(selectValue);
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

//每一项输入框填写
  Column inputTrade(BuildContext context, String TradeName,
      TextEditingController _controller) {
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        new Container(
          child: new Text(TradeName),
          margin: EdgeInsets.only(top: ScreenUtil().setWidth(15)),
          height: ScreenUtil().setWidth(18),
        ),
        new Container(
          height: ScreenUtil().setWidth(48),
          child: new TextField(
            //controller: _controller,    //给出提示选项
            style: TextStyle(color: Colors.black45),
            obscureText: true,

          ),
        ),
      ],
    );
  }

//4.底部按钮组件
  Widget buttonSection_2_4(BuildContext context) => new Container(
        child: new Padding(
          padding: EdgeInsets.only(top: ScreenUtil().setWidth(0)),
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(20),
                ),
                child: new Container(
                  //容器倒角处理
                  decoration: BoxDecoration(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(25)),
                      boxShadow: <BoxShadow>[
                        BoxShadow(color: Colors.white, blurRadius: 2.0)
                      ]),
                  width: ScreenUtil().setWidth(160),
                  height: ScreenUtil().setWidth(48),
                  child: new RaisedButton(
                    //按钮倒角处理
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                          Radius.circular(ScreenUtil().setWidth(25))),
                    ),
                    onPressed: () {
                      showDialog(
                          context: context,
                          //_controller.text 用户正在编辑的当前字符串
                          child: new AlertDialog(
                            title: new Text("Account 信息"),
                            content: new Text('取消消息'),
                          ));
                    },
                    child: new Text(
                      'Cancel',
                      style: TextStyle(
                        color: Color.fromARGB(254, 58, 204, 225),
                        fontSize: ScreenUtil().setSp(16),
                      ),
                    ),
                  ),
                ),
              ),
              new Padding(
                padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(15),
                ),
                child: new Container(
                  //容器倒角处理
                  decoration: BoxDecoration(
                      borderRadius:
                          BorderRadius.circular(ScreenUtil().setWidth(25)),
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                            color: Color.fromARGB(254, 58, 204, 225),
                            blurRadius: 2.0)
                      ]),
                  width: ScreenUtil().setWidth(160),
                  height: ScreenUtil().setWidth(48),
                  child: new RaisedButton(
                    color: Color.fromARGB(254, 58, 204, 225),
                    //按钮倒角处理
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(
                          Radius.circular(ScreenUtil().setWidth(25))),
                    ),
                    onPressed: () {



                    },
                    child: new Text(
                      'Start',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: ScreenUtil().setSp(16),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        height: ScreenUtil().setWidth(78),
      );

//---------------------------------------------------------------------------

}

页面效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43231352/article/details/86416488