Reputation: 3361
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
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
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.
Image source here.
Upvotes: 1