app 开发中,最重要的部分是,咱们需要从服务或者本地获取数据,烘托到咱们的挂件中。

整体作用 Gif 图:

Flutter - ListView 挂件中使用 JSON 文件

下面,咱们依照步骤来在 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(),
    );
  }
}

第 2 步:插入 ListView 挂件

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 文件

Flutter - ListView 挂件中使用 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 文件:

# To add assets to your application, add an assets section, like this:
assets:
- assets/loadjson/details.json

图片资源

Flutter - ListView 挂件中使用 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,
            );
          },
        ),
      ),
    );
  }
}

输出:

Flutter - ListView 挂件中使用 JSON 文件

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,
          ),
        ),
      ),
    );
  }
}

显现作用:

Flutter - ListView 挂件中使用 JSON 文件

本文是译文,采用意译的方法。原文链接:faun.pub/flutter-imp…