Reputation: 196
So I am making an app with flutter. So in the main.dart file i am making a component which is basically a bunch of widgets wrapped together. I have to use this component multiple times so I thought of making these reusable component in another dart file and then importing it in main.dart.
This is my code for reusable.dart
import 'package:flutter/material.dart';
double mainTab = 150;
class TileData extends StatefulWidget {
@override
_TileDataState createState() => _TileDataState();
}
class _TileDataState extends State<TileData> {
@override
Widget build(BuildContext context) {
return Container(
height: 200 - 15.0,
width: mainTab - 10.0,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 15, 0, 0),
child: Column(
),
),
);
}
}
I plan to use this TileData Widget in my main.dart in this manner
ListView(
children: children: <Widget>[
TileData(
children: <Widget>[
Text('Element 1'),
]),
TileData(
children: <Widget>[
Text('Element 2'),
]),
TileData(
children: <Widget>[
Text('Element 3'),
],
)
],
),
So the children of the TileData() widget are actually the children of the column which was last wrapped in the widget in reusable.dart
Is there any way I can achieve this?
Upvotes: 6
Views: 10294
Reputation: 486
You can use ListView.builder()
add Constructor in your TileData
widget
something like
ListView.builder(
itemCount:data.length,
itemBuilder: (context,index){
return TileData(data:"Element $index");
}
)
Upvotes: 0
Reputation: 246
TileDate
import 'package:flutter/material.dart';
double mainTab = 150;
class TileData extends StatefulWidget {
List<Widget> widgetsList;
TileData({this.widgetsList});
@override
_TileDataState createState() => _TileDataState();
}
class _TileDataState extends State<TileData> {
@override
Widget build(BuildContext context) {
return Container(
height: 200 - 15.0,
width: mainTab - 10.0,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 15, 0, 0),
child: Column(
children: widget.widgetsList,
),
),
);
}
}
main
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:test/widgets/TileData.dart';
void main() => runApp(MaterialApp(
home: Scaffold(backgroundColor: Color(0xFF2d3447), body: MyApp()),
));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
children: [
TileData(
widgetsList: [Text("Element 1")],
),
TileData(
widgetsList: [Text("Element 2")],
),
TileData(
widgetsList: [Text("Element 3")],
)
],
);
}
}
In this way u can reuse
Upvotes: 8
Reputation: 647
Create a property and use it as an argument in the constructor of the reusable widget.
final List<Widget> children;
TileData({this.children});
Then, in your build method, pass the property to the column.
Column(
children: widget.children
)
Upvotes: 3