效果图
项目目录里新建一个load_json目录,里面再新建一个person.json文件。
[ { "name" : "Suye", "age" : "27", "height" : "170", "gender" : "male", "hair_color" : "black" }, { "name" : "Surina", "age" : "26", "height" : "160", "gender" : "female", "hair_color" : "brown" }, { "name" : "Terigele", "age" : "25", "height" : "174", "gender" : "male", "hair_color" : "black" } ]
之后在pubspec.yaml里配置引入资源。
这个配置文件比较坑,需要注意缩进格式,多一个或少一个空格就会出错。
之后就是写主函数了。
import 'dart:convert'; import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.teal, ), home: new MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List data; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Center( child: FutureBuilder( future: DefaultAssetBundle. of(context). loadString('load_json/person.json'), builder: (context,snapshot){ // ignore: deprecated_member_use var mydata = JSON.decode(snapshot.data.toString()); return ListView.builder( itemBuilder: (BuildContext context,int index){ return Card( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text("Name:" + mydata[index]["name"]), Text("Age:" + mydata[index]["age"]), Text("Height:" + mydata[index]["height"]), Text("Hair:" + mydata[index]["hair_color"]), Text("Gender:" + mydata[index]["gender"]), ], ), ); }, itemCount: mydata == null ? 0 : mydata.length, ); }, ), ), ); } }
读取json文件需要用到Future,异步操作都会用到,相当于web里的promise。(个人理解,水平有限、轻点喷~有高手路过,请帮忙纠正)
读取后需要解析,需要引入convert库,然后用 JSON.decode(snpashot.data.toSpring())