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站教程。

相关推荐
小蜜蜂嗡嗡6 小时前
flutter项目迁移空安全
javascript·安全·flutter
北极象9 小时前
在Flutter中定义全局对象(如$http)而不需要import
网络协议·flutter·http
明似水10 小时前
Flutter 包依赖升级指南:让项目保持最新状态
前端·flutter
唯有选择15 小时前
flutter_localizations:轻松实现Flutter国际化
flutter
初遇你时动了情1 天前
dart常用语法详解/数组list/map数据/class类详解
数据结构·flutter·list
OldBirds1 天前
Flutter element 复用:隐藏的风险
flutter
爱意随风起风止意难平1 天前
002 flutter基础 初始文件讲解(1)
学习·flutter
OldBirds2 天前
理解 Flutter Element 复用
flutter
hepherd2 天前
Flutter - 原生交互 - 相机Camera - 01
flutter·ios·dart