基于Flutter构建小型新闻App

目录

1. 概述

1.1 功能概述

1.2 技术准备

1.3 源码地址

2. App首页

2.1 pubspec依赖

2.2 热门首页组件

2.2.1 DefaultTabController

2.2.2 Swiper

2.3 新闻API数据访问 

2.4 热门首页效果图

3. 新闻分类

3.1 GestureDetector

3.2 新闻分类效果图

4. 收藏功能

4.1 fluttertoast

4.2 shared_preferences

4.3 收藏效果图

5. 相关文档和总结


最近在研究基于Flutter构建一个简单的新闻资讯app,主要参考:用Flutter极速构建原生应用(需要电子书的话可以私聊),但是这本书有部分代码引用的组件版本已经不适用所以做了一些调整。以下是对于开发过程和遇到的一些问题的总结。

1. 概述

1.1 功能概述

对于Flutter的环境配置就不做总结了,为了节省时间大家可以用IntelliJ IDEA专业版,里面就可以创建Flutter项目。主要包含三个部分:

  • 热门新闻列表。
  • 分类新闻列表。
  • 新闻详情页。
  • 收藏功能。

1.2 技术准备

应用的首页用来展示热门新闻,我们可以选取天行数据的“综合新闻”接口服务,接口服务详细信息地址:综合新闻API接口 - 天行数据TianAPI

在这注册一个账号用来做app测试。

然后创建一个Flutter应用,目录架构如下:

1.3 源码地址

项目源码:基于Flutter构建的新闻App

Git地址:GitHub - BAStriver/flutter_test: test

2. App首页

这里主要引用到DefaultTabController组件和Swiper组件。

  • 使用DefaultTabController组件来实现多模块的聚合页面。
  • 使用Swiper实现首页图片轮播。

首先在category和home文件夹下新建两个Dart文件,命名为category_view.dart与home_view.dart。目前实现如下效果:

2.1 pubspec依赖

如下是这个app的主要依赖设置:

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  http: ^1.1.2
  fluttertoast: ^8.2.4
  shared_preferences: ^2.2.2

2.2 热门首页组件

2.2.1 DefaultTabController

Widget _containerView(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: DefaultTabController(
          length: 2,
          child: Scaffold(
            appBar: AppBar(
              bottom: const TabBar(
                tabs: [
                  Tab(
                    child: Text(
                      "popular",
                      style: TextStyle(color: Colors.black),
                    ),
                  ),
                  Tab(
                    child: Text(
                      "classifications",
                      style: TextStyle(color: Colors.black),
                    ),
                  )
                ],
                indicatorColor: Colors.green,
              ),
              title: const Text(
                "ALl News",
                style: TextStyle(color: Colors.black),
                textAlign: TextAlign.center,
              ),
              backgroundColor: Colors.white,
              actions: <Widget>[
                GestureDetector(
                  child: Container(
                    width: 60,
                    child: const Icon(Icons.collections),
                  ),
                  onTap: () {
                    print('enter collection view.');
                    Navigator.push(context, MaterialPageRoute(builder: (context) {
                      print('enter collection view2.');
                      return CollectionView();
                    }));
                  },
                )
              ],
            ),
            body: TabBarView(
              children: [HomeView(), CategoryView()],
            ),
          )),
    );
  }

2.2.2 Swiper

Widget _buildSwiper(BuildContext context) {
    return Container(
      height: 150,
      child: Swiper(
        pagination: const SwiperPagination(),
        control: const SwiperControl(),
        autoplay: true,
        itemCount: 3,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            margin: const EdgeInsets.only(bottom: 5),
            color: Colors.orange,
            width: MediaQuery.of(context).size.width,
            height: 150,
            child: Image.network(
              _dataList[_dataList.length - 1].picUrl,
              height: 150,
              width: MediaQuery.of(context).size.width,
              fit: BoxFit.fitWidth,
            ),
          );
        },
      ),
    );
  }

这里如果参考书上的写法会有问题,所以为了解决升级到Dart3.0后Swiper不兼容的问题可以参考:由于flutter_app依赖于flutter_swiper>=0.0.2,不支持零安全,版本解决失败。_because book depends on flutter_swiper >=0.0.2 whi-CSDN博客

2.3 新闻API数据访问 

Future<HomeModel> queryHomeData(int page) async {
    var url = Uri.parse('https://apis.tianapi.com/generalnews/index');

    var headers = <String, String>{"Access-Control-Allow-Origin": "*","Content-Type":"application/x-www-form-urlencoded"};
    var body = <String, String>{"key": URL_KEY, "num": "10", "page": "$page"};

    final response = await http.post(url,body: body, headers: headers);
    Map<String, dynamic> jsonMap = json.decode(response.body);
    return HomeModel.fromJson(jsonMap);
  }

这里会涉及到数据模型的构建和加载,可以参考:A value of type 'X' can't be assigned to a variable of type 'List' - 糯米PHP

2.4 热门首页效果图

3. 新闻分类

这里主要引用到GestureDetector组件。

关于新闻分类主页采用网格布局,根据天行数据网上提供的新闻接口定义10个分类。

final List<String> _categorys = [
    "GeneralNews",
    "CarNews",
    "DomesticNews",
     "AnimeNews",
    "FinancialNews",
    "GameNews",
    "InternationalNews",
    "AINews",
    "MilitaryNews",
    "SportNews"
  ];

3.1 GestureDetector

点击一个分类,页面会跳转到分类列表页。

关于详细的组件回调事件可以参考:

Flutter--GestureDetector手势识别组件_flutter gesturedetector-CSDN博客

Widget _getItem(BuildContext context, int index) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 130,
      child: Row(
        children: <Widget>[
          GestureDetector(
            child: Container(
              width: MediaQuery.of(context).size.width / 2,
              color: index % 2 == 0 ? Colors.orange : Colors.blueAccent,
              height: 130,
              child: Center(
                child: Text(
                  _categorys[index * 2],
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 30, color: Colors.white),
                ),
              ),
            ),
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
                return CategoryListView(CATEGORY_KEYS[_categorys[index * 2]]!, _categorys[index * 2]);
              }));
            },
          ),
          GestureDetector(
            child: Container(
              width: MediaQuery.of(context).size.width / 2,
              color: index % 2 == 0 ? Colors.blueAccent : Colors.orange,
              height: 130,
              child: Center(
                child: Text(
                  _categorys[index * 2 +1],
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 30, color: Colors.white),
                ),
              ),
            ),
            onTap: () {
              Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) {
                return CategoryListView(CATEGORY_KEYS[_categorys[index * 2 + 1]]!, _categorys[index * 2 + 1]);
              }));
            },
          )
        ],
      ),
    );
  }

3.2 新闻分类效果图

进入一般新闻的分类页面:

4. 收藏功能

这里主要引用了fluttertoast和shared_preferences组件。

  • fluttertoast实现弹窗效果。
  • shared_preferences实现本地缓存。

4.1 fluttertoast

实现弹窗是否收藏新闻。

Widget _buildItem(BuildContext context, int index) {
    return Container(
      height: 110,
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(bottom: 1),
      color: Colors.amber,
      child: GestureDetector(
        child: Row(
          children: <Widget>[
            Container(
              color: Colors.grey,
              child: Image.network(
                // "http://n.sinaimg.cn/sinakd202124s/162/w550h412/20210204/6706-kirmait9301473.jpg",
                _dataList[index].picUrl,
                width: 130,
                height: 110,
                fit: BoxFit.fitHeight,
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(left: 10, top: 10, right: 10),
                  width: MediaQuery.of(context).size.width - 130 - 20,
                  child: Text(
                    _dataList[index].title,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                    style: const TextStyle(
                        fontSize: 15, fontWeight: FontWeight.bold),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10, top: 5),
                  child: Text(_dataList[index].description),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10, top: 5),
                  child: Text(_dataList[index].ctime),
                ),
              ],
            )
          ],
        ),
        onLongPress: () {
          showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('Do you want to save it ?'),
                  actions: <Widget>[
                    TextButton(
                        onPressed: () {
                          _addCollection(
                              _dataList[index].id, _dataList[index].title);
                          Navigator.of(context).pop();
                        },
                        child: Text('Yes')),
                    TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('No')),
                  ],
                );
              });
        },
      ),
    );
  }

4.2 shared_preferences

实现本地缓存。

void _addCollection(String id, String title) async {
    print('id: ' + id);
    print('title: ' + title);
    SharedPreferences? preferences = await SharedPreferences.getInstance();
    String? data = preferences.getString(id);
    if (data == null) {
      await preferences.setString(id, title);
      Fluttertoast.showToast(msg: 'saved successfully.');
    } else {
      Fluttertoast.showToast(msg: 'the new already existing.');
    }
  }

4.3 收藏效果图

长按新闻。

收藏成功。

 

点击主页右上角的收藏图标进入收藏页面:

5. 相关文档和总结

开发体验初探 - Flutter 中文文档 - Flutter 中文开发者网站 - Flutter

如何搭建flutter开发环境_flutter环境搭建-CSDN博客

Get 请求 | Post 请求 | 将响应结果转为 Dart 对象 | Future 异步调用

注:

1.遇到跨域问题访问不到图片可以参考:

开发环境如需解决跨域问题

flutter for web 带cookie的网络请求跨域问题处理

2.关于GestureDetector组件的用法可以参考:Flutter--GestureDetector手势识别组件

3.关于SharedPreferences组件的用法可以参考:Flutter 数据存储--shared_preferences使用详情

4.遇到:MissingPluginException (MissingPluginException(No implementation found for method... 需要重新启动项目。

5.遇到Navigator无法正常跳转页面时候可以参考:

Flutter无法跳转页面的解决方法(push方法无效) - 简书

Navigator的正确打开方式-CSDN博客

比如第4节开发收藏功能的时候遇到这个无法跳转的问题,main.dart做了如下的修改:

6.Flutter有两个App主题风格可以引用,包括:cupertino(IOS)、material(Android),具体的官方文档可以参考:Cupertino (iOS-style) widgets | Flutter 、Material Components widgets | Flutter

关于这些风格的Widgets用法也可以参考:开启Fluter基础之旅<三>-------Material Design风格组件、Cupertino风格组件、Flutter页面布局篇...-CSDN博客

  • 23
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值