Flutter练习(二)— 两种方式moke本地json 数据

801 阅读2分钟

前言

今天做仿掘金项目时调不通接口,看了下掘金现在用的接口和之前不一样(又没有接口文档),于是并想着直接moke掘金的数据进行页面的渲染吧,该项目已经放到github中,欢迎查看

今天的目标是将分类渲染至页面

准备步骤:

  • 从掘金中直接copy想要的json数据
  • 声明json数据
  • dart中获取json数据
  • 渲染页面

从接口中copy想要的json数据

image.png

声明json数据

声明json 数据需要在pubspec.yml文件中声明json,如下代码

  assets:
    - assets/json/categories.json

执行命令更新即可

flutter packages get

dart中获取json 数据

在这我百度搜索,发现了两种方式

  • 在widget直接获取
  • 在initState方法中获取

在widget中直接获取数据,渲染页面

需要用到FutureBuild,利用DefaultAssetBundle获取json数据,主要代码如下

 FutureBuilder(
     future: DefaultAssetBundle.of(context)
     .loadString('assets/json/categories.json'),
     builder: (context, snapshot) {
       if (snapshot.hasData) {
         _tabList = json.decode(snapshot.data.toString()) as List;
         return TabBar(
           //生成Tab菜单
           isScrollable: true,
           // 可滚动
           controller: _tabController,
           labelColor: primaryColor,
           unselectedLabelColor: firstColor,
           labelStyle: TextStyle(fontSize: 12.0),
           tabs: _tabList
           .map((e) => Tab(
             text: e['category_name'],
           ))
           .toList());
       } else if (snapshot.hasError) {
         return Text('error>>>>>>>>>>>>:${snapshot.error}');
       }
       return new Container(
         color: new Color.fromRGBO(244, 245, 245, 1.0),
       );
     }),

在initState方法中获取

利用rootBundle.loadString() 方法加载json数据

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    rootBundle
        .loadString("assets/json/categories.json")
        .then((value) => {_tabList = json.decode(value)});
    _tabController = TabController(
        length: _tabList.length,
        vsync: this); 
  }

页面渲染

return Scaffold(
      appBar: TabBar(
          controller: _tabController,
          isScrollable: true,
          // 可滚动
          labelColor: primaryColor,
          unselectedLabelColor: firstColor,
          labelStyle: TextStyle(fontSize: 12.0),
          tabs: _tabList
              .map((e) => Tab(
                    text: e['category_name'],
                  ))
              .toList()),
      body: new TabBarView(
        controller: _tabController,
        children: _tabList.map((e) {
          //创建3个Tab页
          return Container(
            alignment: Alignment.center,
            child: Text(e['category_url'], textScaleFactor: 5),
          );
        }).toList(),
      ),
    );

页面完整代码如下

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application/config/theme.dart';

class IndexPage extends StatefulWidget {
  _IndexState createState() => _IndexState();
}

class _IndexState extends State<IndexPage> with TickerProviderStateMixin {
  late TabController _tabController;
  var _tabList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    rootBundle
        .loadString("assets/json/categories.json")
        .then((value) => {_tabList = json.decode(value)});
    _tabController = TabController(
        length: _tabList.length,
        vsync: this); // categories 的长度为8 ,通常获取类目是走接口,我这边直接moke了json数据
    _tabController.addListener(() {
      switch (_tabController.index) {
        //  TODO 接入 tabBarView
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TabBar(
          controller: _tabController,
          isScrollable: true,
          // 可滚动
          labelColor: primaryColor,
          unselectedLabelColor: firstColor,
          labelStyle: TextStyle(fontSize: 12.0),
          tabs: _tabList
              .map((e) => Tab(
                    text: e['category_name'],
                  ))
              .toList()),
      body: new TabBarView(
        controller: _tabController,
        children: _tabList.map((e) {
          //创建3个Tab页
          return Container(
            alignment: Alignment.center,
            child: Text(e['category_url'], textScaleFactor: 5),
          );
        }).toList(),
      ),
    );
  }
}

效果图如下

image.png