Carrein
Carrein

Reputation: 3361

Encapsulating a widget in its own class in flutter?

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.

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?

Example:

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),
        ...

Upvotes: 3

Views: 8746

Answers (2)

Phuc Tran
Phuc Tran

Reputation: 8073

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

Upvotes: 6

Suragch
Suragch

Reputation: 511626

Generally when creating a widget constructor you also add a Key and call super. Variables should also be marked final since widgets are immutable.

class Tile extends StatelessWidget {

  // make these final
  final String text;
  final String time;

  // constructor
  const Tile({Key key, this.text, this.time}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      // ...
    );
  }
}

And call it like this:

Tile(text: 'hello', time: '5:30');

It is so common to create custom constructors that there is even a shortcut for it in Android Studio.

  1. Write the names of your final variables.
  2. Put your cursor on them and press Option+Retern (or Alt+Enter).

enter image description here

Image source here.

Upvotes: 1

Related Questions