flutter 带你玩转flutter读取本地json并展示UI

前言导读

最近又重新学习flutter ,所以准备做一期分享,相信很多同学都有参加过各种比赛项目 主要都是做一些UI上面的展示 这时候很多同学可能会在本地创建很多数组模拟数据这样代码不但看着很臃肿也不好去处理新增数据。那么我们是不是可以读取本地的json数据然后再去展示UI呢

效果图

json 数据

json 复制代码
{
  "msg": "获取数据成功",
  "code": 200,
  "data": [
    {
      "id": 4,
      "name": "资深iOS工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "12k-18k",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 5,
      "name": "初级GOLang工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 6,
      "name": "中级前端工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 7,
      "name": "资深cocos2D工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 8,
      "name": "资深U3d工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 9,
      "name": "资深PHP工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 10,
      "name": "资深数据挖掘工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 11,
      "name": "资深运维工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 12,
      "name": "资深安卓工程师",
      "cname": "今日头条",
      "size": "D轮",
      "salary": "40K-60K",
      "username": "Kimi",
      "title": "HR"
    },
    {
      "id": 13,
      "name": "移动端架构师",
      "cname": "银汉游戏",
      "size": "B轮",
      "salary": "15K-20K",
      "username": "刘丽",
      "title": "人事主管"
    },
    {
      "id": 14,
      "name": "Java工程师",
      "cname": "37互娱",
      "size": "D轮",
      "salary": "25K-30K",
      "username": "Reiki",
      "title": "HR-M"
    }
  ]
}

我们需要把json文件放在我们的本地工程的data目录下面

我们在pubspec.yaml 文件中加上我们的本地json的配置

dart 复制代码
assets:
  - data/position.json

读取本地json

dart 复制代码
void  getInfo() async{
  final String jsonString = await rootBundle.loadString('data/position.json');
  print("jsonString  -- >"+jsonString);
  PositionInfo positionInfo=PositionInfo.fromJson(json.decode(jsonString));
  setState(() {

    String?msg=positionInfo.msg;
    int? code =positionInfo.code;
    if(code==200){
      _getdata=positionInfo.data!;
      print(_getdata.toString());
    }
  });

}

positioninfo 数据模型代码

dart 复制代码
/***
 * 创建人:xuqing
 * 创建时间:2020年3月9日19:21:24
 * 类说明:职位信息 模型类
 *
 *
 *
 */

class PositionInfo {
    List<Data>? data;
    int ?code;
    String? msg;
    PositionInfo({this.data, this.code, this.msg});
    factory PositionInfo.fromJson(Map<String, dynamic> json) {
        return PositionInfo(
            data: json['data'] != null ? (json['data'] as List).map((i) => Data.fromJson(i)).toList() : null, 
            code: json['code'], 
            msg: json['msg'], 
        );
    }
    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['code'] = this.code;
        data['msg'] = this.msg;
        if (this.data != null) {
            data['data'] = this.data!.map((v) => v.toJson()).toList();
        }
        return data;
    }
}

class Data {
    String? cname;
    int ?id;
    String? name;
    String? salary;
    String? size;
    String? title;
    String? username;
    Data({this.cname, this.id, this.name, this.salary, this.size, this.title, this.username});
    factory Data.fromJson(Map<String, dynamic> json) {
        return Data(
            cname: json['cname'], 
            id: json['id'], 
            name: json['name'], 
            salary: json['salary'], 
            size: json['size'], 
            title: json['title'] ,
            username: json['username'], 
        );
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['cname'] = this.cname;
        data['id'] = this.id;
        data['name'] = this.name;
        data['salary'] = this.salary;
        data['size'] = this.size;
        data['username'] = this.username;
        data['title']=this.title;
        return data;
    }
}

解析json 转换成model

dart 复制代码
PositionInfo positionInfo=PositionInfo.fromJson(json.decode(jsonString));

在我们的初始化生命周期方法里面调用

dart 复制代码
@override
void initState() {
  super.initState();
  getInfo();
}

UI 部分代码

dart 复制代码
@override
Widget build(BuildContext context) {
  // TODO: implement build
  return Scaffold(
     appBar: AppBar(
       title: Text("职位11",style: TextStyle(
          color: Colors.white,
          fontSize: 20
       ),),
       centerTitle:true,
     ),
      body: Container(
        child: new ListView.builder(
          itemCount: (_getdata==null)?0:_getdata.length,
          itemBuilder: (BuildContext context, int position){
            return getItem(position);
          },
        )
      ),
  );
}

listview item 代码

dart 复制代码
Widget getItem(int index){
  data=_getdata[index];
  return  new Padding(padding: EdgeInsets.only(
      top: 3.0,
      left: 5.0,
      right: 5.0,
      bottom: 3.0
  ),
    child: new SizedBox(
      child: Card(
        elevation: 0.0,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Expanded(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    new  Row(
                      children: <Widget>[
                        new Padding(padding:

                        EdgeInsets.only(
                            top: 10.0,
                            left: 10.0,
                            bottom: 5.0
                        ),
                          child: new Text(data!.name!),
                        ),
                        new Expanded(
                            child:Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: <Widget>[
                                new Padding(padding: EdgeInsets.only(
                                    right: 10.0
                                ),
                                  child:  Text(
                                    data!.salary!,
                                    style: TextStyle(
                                        color: Colors.red
                                    ),
                                  ),
                                )
                              ],
                            )
                        ),
                      ],
                    ),
                    new Container(
                      child: new Text(data!.name!+data!.size!,
                        textAlign: TextAlign.left,
                        style: new TextStyle(
                            fontSize: 20.0,
                            color: Colors.grey
                        ),
                      ),
                      margin: EdgeInsets.only(
                          top: 5.0,
                          left: 10.0,
                          bottom: 5.0
                      ),
                    ),
                    new  Divider(),
                    new Row(
                      children: <Widget>[

                        new Padding(padding: EdgeInsets.only(
                          top: 5.0,
                          left: 10.0,
                          right: 5.0,
                          bottom: 15.0,
                        ),
                          child: new Text(
                            data!.username!+"|"+data!.title!,
                            style: TextStyle(
                                color: new Color.fromARGB(255, 0, 215, 198)
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                )
            ),
          ],
        ),
      ),
    ),
  );
}

完整UI代码

dart 复制代码
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttergetfilejson/positioninfo.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:Scaffold(
        body: HomePage(),
      )
    );
  }
}


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

  @override
  _HomePageState createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {

  List  _getdata=[];
  Data ? data=null ;
  @override
  void initState() {
    super.initState();
    getInfo();
  }

  void  getInfo() async{
    final String jsonString = await rootBundle.loadString('data/position.json');
    print("jsonString  -- >"+jsonString);
    PositionInfo positionInfo=PositionInfo.fromJson(json.decode(jsonString));
    setState(() {

      String?msg=positionInfo.msg;
      int? code =positionInfo.code;
      if(code==200){
        _getdata=positionInfo.data!;
        print(_getdata.toString());
      }
    });

  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
       appBar: AppBar(
         title: Text("职位11",style: TextStyle(
            color: Colors.white,
            fontSize: 20
         ),),
         centerTitle:true,
       ),
        body: Container(
          child: new ListView.builder(
            itemCount: (_getdata==null)?0:_getdata.length,
            itemBuilder: (BuildContext context, int position){
              return getItem(position);
            },
          )
        ),
    );
  }

  Widget getItem(int index){
    data=_getdata[index];
    return  new Padding(padding: EdgeInsets.only(
        top: 3.0,
        left: 5.0,
        right: 5.0,
        bottom: 3.0
    ),
      child: new SizedBox(
        child: Card(
          elevation: 0.0,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Expanded(
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      new  Row(
                        children: <Widget>[
                          new Padding(padding:

                          EdgeInsets.only(
                              top: 10.0,
                              left: 10.0,
                              bottom: 5.0
                          ),
                            child: new Text(data!.name!),
                          ),
                          new Expanded(
                              child:Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: <Widget>[
                                  new Padding(padding: EdgeInsets.only(
                                      right: 10.0
                                  ),
                                    child:  Text(
                                      data!.salary!,
                                      style: TextStyle(
                                          color: Colors.red
                                      ),
                                    ),
                                  )
                                ],
                              )
                          ),
                        ],
                      ),
                      new Container(
                        child: new Text(data!.name!+data!.size!,
                          textAlign: TextAlign.left,
                          style: new TextStyle(
                              fontSize: 20.0,
                              color: Colors.grey
                          ),
                        ),
                        margin: EdgeInsets.only(
                            top: 5.0,
                            left: 10.0,
                            bottom: 5.0
                        ),
                      ),
                      new  Divider(),
                      new Row(
                        children: <Widget>[

                          new Padding(padding: EdgeInsets.only(
                            top: 5.0,
                            left: 10.0,
                            right: 5.0,
                            bottom: 15.0,
                          ),
                            child: new Text(
                              data!.username!+"|"+data!.title!,
                              style: TextStyle(
                                  color: new Color.fromARGB(255, 0, 215, 198)
                              ),
                            ),
                          )
                        ],
                      )
                    ],
                  )
              ),
            ],
          ),
        ),
      ),
    );
  }


}

最后总结

flutter里面读取本地json比较简单 我们拿到本地json后 去解析的时候我们需要 json.decode(jsonString) ,然后我们这个读取的操作 最好是异步去操作。拿到数据后我们可以再去操作解析数据和显示UI , 读取本地json主要是模拟一些数据的时候比较方面。今天的文章就讲到这里,有更多需要了解的可以关注我的B站教程。

相关推荐
奋斗的小青年!!2 小时前
Flutter浮动按钮在OpenHarmony平台的实践经验
flutter·harmonyos·鸿蒙
程序员老刘6 小时前
一杯奶茶钱,PicGo + 阿里云 OSS 搭建永久稳定的个人图床
flutter·markdown
奋斗的小青年!!9 小时前
OpenHarmony Flutter 拖拽排序组件性能优化与跨平台适配指南
flutter·harmonyos·鸿蒙
小雨下雨的雨10 小时前
Flutter 框架跨平台鸿蒙开发 —— Stack 控件之三维层叠艺术
flutter·华为·harmonyos
行者9611 小时前
OpenHarmony平台Flutter手风琴菜单组件的跨平台适配实践
flutter·harmonyos·鸿蒙
小雨下雨的雨13 小时前
Flutter 框架跨平台鸿蒙开发 —— Flex 控件之响应式弹性布局
flutter·ui·华为·harmonyos·鸿蒙系统
cn_mengbei13 小时前
Flutter for OpenHarmony 实战:CheckboxListTile 复选框列表项详解
flutter
cn_mengbei13 小时前
Flutter for OpenHarmony 实战:Switch 开关按钮详解
flutter
奋斗的小青年!!13 小时前
OpenHarmony Flutter实战:打造高性能订单确认流程步骤条
flutter·harmonyos·鸿蒙
Coder_Boy_13 小时前
Flutter基础介绍-跨平台移动应用开发框架
spring boot·flutter