在窗口小部件中将小部件封装在自己的类中? [英] Encapsulating a widget in it's own class in flutter?

查看:60
本文介绍了在窗口小部件中将小部件封装在自己的类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 listview 创建一个 tile .当磁贴放置在listview文件中时,该磁贴正在工作,我想知道如何将 tile 小部件封装到其自己的类文件中.

I'm trying to create a tile for my listview. While the tile is working when placed within the listview file, I'm wondering how would I go about encapsulating the tile widget into its own class file.

具体来说,如果 tile 对象不带参数,我可以简单地扩展无状态小部件并调用 build 方法以返回一个新的tile对象.但是,如果要使用参数(即自定义文本)创建tile对象,该如何传递这些信息?还是将小部件留在 listview 类本身中会更好?

Specifically, if the tile object does not take an argument, I can simply extend a stateless widget and call upon the build method to return a new tile object. But if the tile object is to be created with arguments (i.e. custom text), how do I pass this information along? Or would it be better to leave the widget in the listview class itself?

示例:

class Tile extends StatelessWidget {

  @override
  Widget build(BuildContext context){
    return _tile(); //Error, How do i pass the arguments?
  }
  Widget _tile(String text, String time) {
    return new Align(
      child: new Container(
        // padding: EdgeInsets.all(5.0),
        ...

推荐答案

我认为您可以简单地创建一个构造函数并使用它

I think you can simply create a constructor and use it

import 'package:flutter/material.dart';

class Tile extends StatelessWidget {
  final String text;
  final String time;

  /// Here is your constructor
  Tile({Key key, this.text, this.time});

  @override
  Widget build(BuildContext context) {
    return _buildTitle(this.text, this.time);
  }

  Widget _buildTitle(String text, String time) {
    return new Align(
        child: new Container(
          // padding: EdgeInsets.all(5.0),
        ));
  }
}

这篇关于在窗口小部件中将小部件封装在自己的类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆