i have Method and Widget section defined in main.dart and my code works fine,
i created new file method.dart and used all methods in that file and imported methods in my main file and it worked,
but my issue is how i can call Widget section from another file in main.dart.
main.dart:
how to call following widget from another file:
Widget buttonSection = Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(color, Icons.call, 'CALL'),
_buildButtonColumn(color, Icons.near_me, 'ROUTE'),
_buildButtonColumn(color, Icons.share, 'SHARE'),
],
),
);
following method can be called from another file:
Column _buildButtonColumn(Color color, IconData icon, String label) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Container(
margin: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
Using it in material function:
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter layout demo'),
),
body: ListView(
children: [
Image.asset(
'images/lake.jpg',
width: 600,
height: 240,
fit: BoxFit.cover,
),
buttonSection,
],
),
),
);
To use your buttonSection widget from any file whether it is main.dart file or any other dart file you have to write the buttonSection widget out of any class and globally.
So you can have the access of that particular widget. If you are creating it inside a Stateful or Stateless class then you will not be able to access the buttonSection widget.
So create a dart file and add the following widget out of all class and define globally.
Widget buttonSection = Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButtonColumn(color, Icons.call, 'CALL'),
_buildButtonColumn(color, Icons.near_me, 'ROUTE'),
_buildButtonColumn(color, Icons.share, 'SHARE'),
],
),
);
Then to access it anywhere import the dart file containing buttonSection widget and you can use it like,
@override
Widget build(BuildContext context) {
return buttonSection;
}
Also, keep in mind that your widget/variable/function name should not start with "_" to globally access it from another dart files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With