当前位置: 首页 > news >正文

Flutter学习笔记 —— 完成一个简单的新闻展示页

Flutter学习笔记 —— 完成一个简单的新闻展示页

  • 前言
  • 思路分析
  • 案例代码
  • 结束语

在这里插入图片描述

上图

前言

刚学Flutter不久,今天我们来看看如何使用 Container & ListView实现一个简单的新闻展示页

思路分析

主要使用:Scaffold 实现页面
组件列表 (我习惯叫组件)

  1. StatelessWidget(主界面)
  2. StateFulWidget(新闻内容)
  3. 两个State(用于展示给基类数据、主界面数据)
  4. Entity(实体类)

看起来需要很多,但是实际上实现起来非常简单

案例代码

StatelessWidget.dart

void main() => runApp(TestApp());

class TestApp extends StatelessWidget{
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "My App",
      debugShowCheckedModeBanner: false,
      home: new SimpleWidget(AppState()),
    );
  }

}

Entity -> Recommand

/**
 *  新闻推荐内容
 */
class Recommand{
   final String _image;
   final String _context;

   Recommand(this._image,this._context);

   get getImage => _image;

   get getContext => _context;

}

Entity -> Content

import 'Recommend.dart';
import 'package:flutter/material.dart';
class Content{
  List<Recommand> recommandList = [];
  Content.load(){
    _defaultRecommandList();
  }

  void _defaultRecommandList(){
    recommandList.add(new Recommand("http://contentcms-bj.cdn.bcebos.com/cmspic/c86c3bdba9c2cb410b37365f0ba62a05.jpeg?x-bce-process=image/crop,x_0,y_0,w_1987,h_1082", "这是新闻内容。。"));
    recommandList.add(new Recommand("http://contentcms-bj.cdn.bcebos.com/cmspic/a5ad81b7fc2df3c172bf515a139492d2.jpeg?x-bce-process=image/crop,x_0,y_0,w_1627,h_885", "这是新闻内容。。"));
    recommandList.add(new Recommand("http://contentcms-bj.cdn.bcebos.com/cmspic/af9f3160d4513171ff7dd3c4a791b931.jpeg?x-bce-process=image/crop,x_0,y_0,w_2104,h_1144", "这是新闻内容。。"));
    recommandList.add(new Recommand("http://contentcms-bj.cdn.bcebos.com/cmspic/fa645ad8b521ed00391c1889cf0fc2a2.jpeg?x-bce-process=image/crop,x_0,y_0,w_1627,h_887", "这是新闻内容。。"));
    recommandList.add(new Recommand("http://contentcms-bj.cdn.bcebos.com/cmspic/187da77d7d0b07906285f7c961d6dd74.jpeg?x-bce-process=image/crop,x_0,y_0,w_2023,h_1101", "这是新闻内容。。"));
  }

  List<Widget> getContentWidgetList(){
    List<Widget> titleList = [];
    for(var i = 0;i<this.recommandList.length;i++){
      var data = this.recommandList[i];
      titleList.add(ListTile(
        contentPadding: EdgeInsets.fromLTRB(0,0,0, 50),
        leading: Image.network(data.getImage,fit: BoxFit.cover,alignment: AlignmentDirectional.topStart,width: 50,height: 50),
        title: new Text(data.getContext,style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold,fontSize: 15)),
      ));
    }
    return titleList;
  }


}

SimpleWidget

import "package:flutter/material.dart";
import "package:fluttermytest/components/State.dart";
class SimpleWidget extends StatefulWidget{

  State<SimpleWidget> _state;
  SimpleWidget(this._state);

  
  State<StatefulWidget> createState() {
    return this._state;
  }

}

定义初始基类用于展示内容


class NewsBasicWidget extends StatelessWidget{



  
  Widget build(BuildContext context) {

    return MaterialApp(
      title: "Marinda My App",
      color: Colors.blue,
      home: Container(
        height: 300,
        width: 300,
        child: new SimpleWidget(NewsState())
      )
    );
  }

}

定义主要实现State

import "package:flutter/material.dart";
import 'package:fluttermytest/components/Widget.dart';
import 'package:fluttermytest/components/Basic.dart';
import 'package:fluttermytest/entity/Content.dart';
import 'package:fluttermytest/entity/Recommend.dart';

/**
 * AppState 主要实现State
 */
class AppState extends State<SimpleWidget>{

  //初始化页面
  List<Widget> pageWidgetList = [
    NewsBasicWidget(),
    NewsBasicWidget(),
    NewsBasicWidget(),
  ];

  int index = 0;

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("My Marinda App"),
      ),
      body: pageWidgetList[index],
      bottomNavigationBar: BottomNavigationBar(items: [
        new BottomNavigationBarItem(icon: Icon(Icons.add_alert),label: "最新咨询"),
        new BottomNavigationBarItem(icon: Icon(Icons.settings),label: "设置"),
        new BottomNavigationBarItem(icon: Icon(Icons.account_box),label: "我的"),
      ],onTap: (flag){
        index = flag;
        print(index);
        setState(() {

        });
      },currentIndex: index,),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
          onPressed: (){
          print("被点击!");
      },
          hoverColor: Colors.blue,
          focusColor: Colors.red,
          backgroundColor: Colors.orange,
        child: new Text("新增"),
      ),
      persistentFooterAlignment: AlignmentDirectional.bottomEnd,
      persistentFooterButtons: <Widget>[
        new Text("内容!")
      ],
      //左滑
      drawer: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
        child: TextButton.icon(onPressed: ()=>print("新增!"), icon: Icon(Icons.add), label: Text("新增",style: TextStyle(color: Colors.white))),
      ),
      endDrawer: Container(
        width: 100,
        height: 100,
        color: Colors.blue,
        child: TextButton.icon(onPressed: ()=>print("删除!"), icon: Icon(Icons.add), label: Text("删除",style: TextStyle(color: Colors.white))),
      ),
    );
  }
}

/**
 *  新闻state 给基类用于展示
 */
class NewsState extends State<SimpleWidget>{
  
  Widget build(BuildContext context) {
    Content content = Content.load();
    // int len = content.recommandList.length;
    return ListView(
      padding: new EdgeInsets.all(30),
      // scrollDirection: Axis.vertical,
      children: content.getContentWidgetList(),
    );
  }

}

//主界面展示
class ScaffoldTest extends State<SimpleWidget>{
  int _index = 0;

  List<Widget> pageWidgetList = [

    SimpleBasicWidget("正文一"),
    SimpleBasicWidget("正文二"),
    SimpleBasicWidget("正文三"),
  ];
  
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("内容信息"),
      ),
      body: pageWidgetList[_index],
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          print("点击!");
        },
        child: Text("++"),
        tooltip: "点击了tooltip",
        backgroundColor: Colors.red,
        focusColor: Colors.green,
        splashColor: Colors.deepOrange,
        elevation: 0.0,
        highlightElevation: 20.0,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      persistentFooterButtons: <Widget>[
        Text("标签页")
      ],
      drawer: Container(
        alignment: Alignment.topLeft,
        color: Colors.blue,
        width: 120,
        height: 50,
        child: new TextButton(onPressed: (){
          Navigator.of(context).pop();
        }, child: new Text("点我",style: TextStyle(color: Colors.red),)),
      ),
      endDrawer: Container(
        alignment: Alignment.center,
        color: Colors.yellow,
        width: 120,
        height: 50,
        child: new TextButton(onPressed: (){
          Navigator.of(context).pop();
        }, child: new Text("右滑菜单")),
      ),
      bottomNavigationBar: new BottomNavigationBar(items: [
        BottomNavigationBarItem(icon: Icon(Icons.home,color: _index==0 ? Colors.red : Colors.black),label: "主页"),
        BottomNavigationBarItem(icon: Icon(Icons.home,color: _index==1 ? Colors.red : Colors.black),label: "副页"),
        BottomNavigationBarItem(icon: Icon(Icons.home,color: _index==2 ? Colors.red : Colors.black),label: "收藏"),
      ],
        onTap: (flag){
        print(flag);
        _index = flag;
        setState(() {

        });
        },currentIndex: _index,
      ),
    );
  }

}


结束语

Flutter学习笔记 —— 完成一个简单的新闻展示页

  • 如果对你有帮助的话可以给我点赞收藏,十分感谢
  • 致力做学习笔记分享给大家
  • 可以转载 需标明 出处 本文链接。

感谢你的观看。

相关文章:

  • pytorch 常见的网络层(卷积层,池化层,线性层,激活函数)
  • java计算机毕业设计计算机系教师教研科研管理系统源码+数据库+系统+lw文档+mybatis+运行部署
  • Redis持久化机制
  • 大数据随记 —— DataFrame 与 RDD 之间的相互转换
  • React 学习笔记 2022-08
  • 【实用工具系列之爬虫】python爬取资讯数据
  • 易基因|植物育种:ChIP-seq(组蛋白)揭示H3K36me修饰影响温度诱导的植物可变剪接和开花
  • java计算机毕业设计计算机组成原理教学演示软件源码+数据库+系统+lw文档+mybatis+运行部署
  • Elasticsearch:简体繁体转换分词器 - STConvert analysis
  • C语言经典算法实例1:求二维数组最大最小值
  • 【C++入门基础】命名空间 | 缺省参数 | 函数重载 | 引用 | 内联函数
  • VMware安装与配置Linux 虚拟机
  • Code For Better 谷歌开发者之声——我与Android同成长
  • 【深度学习】(五)目标检测——下篇
  • web前端面试高频考点——Vue3.0新增API(生命周期,ref、toRef 和 toRefs 的理解和最佳使用方式)
  • Babel配置的不完全指南
  • MaxCompute访问TableStore(OTS) 数据
  • Node项目之评分系统(二)- 数据库设计
  • PHP面试之三:MySQL数据库
  • React-Native - 收藏集 - 掘金
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • spring-boot List转Page
  • SQLServer之索引简介
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 后端_MYSQL
  • 开源中国专访:Chameleon原理首发,其它跨多端统一框架都是假的?
  • postgresql行列转换函数
  • ​二进制运算符:(与运算)、|(或运算)、~(取反运算)、^(异或运算)、位移运算符​
  • ###51单片机学习(1)-----单片机烧录软件的使用,以及如何建立一个工程项目
  • #前后端分离# 头条发布系统
  • #图像处理
  • (16)UiBot:智能化软件机器人(以头歌抓取课程数据为例)
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (二)换源+apt-get基础配置+搜狗拼音
  • (六)Hibernate的二级缓存
  • (求助)用傲游上csdn博客时标签栏和网址栏一直显示袁萌 的头像
  • (十)【Jmeter】线程(Threads(Users))之jp@gc - Stepping Thread Group (deprecated)
  • (转)甲方乙方——赵民谈找工作
  • (自适应手机端)响应式新闻博客知识类pbootcms网站模板 自媒体运营博客网站源码下载
  • .gitignore文件使用
  • .java 9 找不到符号_java找不到符号
  • .libPaths()设置包加载目录
  • .naturalWidth 和naturalHeight属性,
  • .NET牛人应该知道些什么(2):中级.NET开发人员
  • .NET值类型变量“活”在哪?
  • .py文件应该怎样打开?
  • /var/log/cvslog 太大
  • @KafkaListener注解详解(一)| 常用参数详解
  • @test注解_Spring 自定义注解你了解过吗?
  • [AIGC] SQL中的数据添加和操作:数据类型介绍
  • [BUAA软工]第一次博客作业---阅读《构建之法》
  • [BZOJ 1032][JSOI2007]祖码Zuma(区间Dp)
  • [BZOJ 2142]礼物(扩展Lucas定理)
  • [BZOJ2850]巧克力王国
  • [C++]指针与结构体