欢迎大家来到IT世界,在知识的湖畔探索吧!
#头条创作挑战赛#
本文同步本人掘金平台的原创翻译:https://juejin.cn/post/7152383584844644366
在 app 开发中,最重要的部分是,我们需要从服务或者本地获取数据,渲染到我们的挂件中。
整体效果 Gif 图:
下面,我们按照步骤来在 ListView 挂件中使用 JSON 文件:
第 1 步:创建一个 Flutter 项目
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Listview using local json file'),
),
body: Center(),
);
}
}
复制代码
欢迎大家来到IT世界,在知识的湖畔探索吧!
第 2 步:插入 ListView 挂件
欢迎大家来到IT世界,在知识的湖畔探索吧!body: Center(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32,
bottom: 32,
left: 16,
right: 16,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: () {},
child: Text(
'Country',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
),
Text(
'Capital',
style: TextStyle(
color: Colors.grey.shade600,
),
)
],
),
Container(
height: 50,
width: 50,
child: Image.asset('assets/images/face1.jpg'),
),
],
),
),
);
}
itemCount: 5,
),
),
复制代码
第 3 步:在 assets 文件夹中创建 JSON 文件
[ { "title": "Yogita", "text": "Kumar", "img": "assets/images/face1.jpeg" }, { "title": "Abhishek", "text": "Kumar", "img": "assets/images/face1.jpeg" }, { "title": "Shashwat Kumar", "text": "Singh", "img": "assets/images/face1.jpeg" }, { "title": "Advika", "text": "Singh", "img": "assets/images/face1.jpeg" }, { "title": "Yamini", "text": "Gupta", "img": "assets/images/face1.jpeg" }, { "title": "Nisha", "text": "Rawal", "img": "assets/images/face1.jpeg" }, { "title": "Bhavesh", "text": "Joshi", "img": "assets/images/face1.jpeg" }, { "title": "Rahul", "text": "Khanna", "img": "assets/images/face1.jpeg" }]复制代码
编辑 pubspec.yaml 文件:
欢迎大家来到IT世界,在知识的湖畔探索吧!# To add assets to your application, add an assets section, like this:
assets:
- assets/loadjson/details.json
复制代码
图片资源
第 4 步:从 details.json 文件中解码并获取数据
先导入 dart:convert。
import 'dart:convert';
复制代码
然后声明类型为 List 的变量。
List data;
复制代码
将下面的代码添加上去:
FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/loadjson/details.json'),
builder: (context, snapshot) {
// Decode the JSON
data = json.decode(snapshot.data.toString());
复制代码
FutureBuilder:一旦从未来返回结果,就会构建小挂件。
future:此参数接收结果并将结果发送到 Builder。
builder:此参数接收来自 feature 的数据并返回给小挂件。可以在此处对接接收到的数据并执行任何操作。
initialData:可选的参数,如果我们设置 initialData 参数的值,builder 将会在 future 返回数据前展示 initialData。
这里的 loadString() 函数是用来获取本地 JSON 文件。
future 参数接收到函数返回来的数据之后,将数据传递给 futureBuilder 参数。
builder 解析字符串并返回生成的 Json 对象。
第 5 步:将获取的 JSON 文件的数据写入 ListView 挂件中
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32,
bottom: 32,
left: 16,
right: 16,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => Welcome()),
);
},
child: Text(
data[index]['title'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
),
Text(
data[index]['text'],
style: TextStyle(
color: Colors.grey.shade600,
),
)
],
),
Container(
height: 50,
width: 50,
child: Image.asset(data[index]['img']),
),
],
),
),
);
},
itemCount: data == null ? 0 : data.length,
);
复制代码
itemCount 允许我们在 ListView 挂件中显示所需的条数。
最终的程序 main.dart:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'welcome.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List data = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView using local json file'),
),
body: Center(
child: FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/loadjson/details.json'),
builder: (context, snapshot) {
data = json.decode(snapshot.data.toString());
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.only(
top: 32,
bottom: 32,
left: 16,
right: 16,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => Welcome()),
);
},
child: Text(
data[index]['title'],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
),
Text(
data[index]['text'],
style: TextStyle(
color: Colors.grey.shade600,
),
)
],
),
Container(
height: 50,
width: 50,
child: Image.asset(data[index]['img']),
),
],
),
),
);
},
itemCount: data == null ? 0 : data.length,
);
},
),
),
);
}
}
复制代码
输出:
welcome.dart 文件资源:
import 'package:flutter/material.dart';
class Welcome extends StatefulWidget {
@override
_WelcomeState createState() => _WelcomeState();
}
class _WelcomeState extends State<Welcome> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Welcome'),
),
body: Center(
child: Text(
"You are Welcome",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
复制代码
显示效果:
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/35396.html