Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Flutter code for lab practice

The document is a Flutter lab practice manual that provides code examples for various Flutter widgets and functionalities, including displaying images, videos, text fields, form validation, and dropdown lists. It covers both local and network images, as well as navigation between pages and styling elements like buttons and containers. Each section includes sample code and explanations for implementing these features in a Flutter application.

Uploaded by

Chanyalew 21
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Flutter code for lab practice

The document is a Flutter lab practice manual that provides code examples for various Flutter widgets and functionalities, including displaying images, videos, text fields, form validation, and dropdown lists. It covers both local and network images, as well as navigation between pages and styling elements like buttons and containers. Each section includes sample code and explanations for implementing these features in a Flutter application.

Uploaded by

Chanyalew 21
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 66

Flutter lab practice manual

1. Displaying an image widget in the app


import 'package:flutter/material.dart';
// function to start app building
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root
// of your application
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text(
'Insert Image in the mobile app Demo',
),
),
body: Center(
child: Row(
children: <Widget>[
Image.asset(
'assets/images/mobile.jpeg',
height: 200,
width: 200,
),
Image.asset(
'assets/images/flutter.jpeg',
height: 200,
width: 200,
),
], //<Widget>[]
), //Column
), //Center
),
);
}
}
2. Display network(internet) image

import
'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends
StatelessWidget {
@override
Widget build(BuildContext
context) {
return MaterialApp(

debugShowCheckedModeBanner:
false,
home:
NetworkImageScreen(),
);
}
}

class NetworkImageScreen extends


StatelessWidget {
final String imageUrl =
'https://images.unsplash.com/pho
to-1606787366850-de6330128bfc';
// Replace with your own image
URL

@override
Widget build(BuildContext
context) {
return Scaffold(
appBar: AppBar(title:
Text('displaying Network Image
Example')),
body: Center(
child: Image.network(
imageUrl,
loadingBuilder:
(context, child,
loadingProgress) {
if (loadingProgress
== null) return child;
return Center(
child:
CircularProgressIndicator(
value:
loadingProgress.expectedTotalByt
es != null ?
loadingProgress.cumulativeBytesL
oaded
/(loadingProgress.expectedTotalB
ytes ?? 1)
: null,
),
);
},
errorBuilder:
(context, error, stackTrace) {
return Text('Failed to load
image',
style: TextStyle(color:
Colors.red));
},
fit: BoxFit.cover,
width: 300,
height: 300,
),
),
);
}
}
Output…
To display a video from assets in a Flutter app,
you can use the video_player package. Here’s
how you can do it step by step.
Steps to Display Video from Assets:
Add the video_player package to your
pubspec.yaml:
dependencies:
flutter:
sdk: flutter
video_player: ^2.4.5 # Check for the latest
version
Run flutter pub get in your terminal to install
the package.

Prepare the video file:


Add your video file to the assets folder in your
project (e.g., assets/video/your_video.mp4).
Make sure you add the video file to the
pubspec.yaml under the assets section.
flutter:
assets:
- assets/video/your_video.mp4
3.Flutter route and navigation
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: RunMyApp(),
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.green),
));
}
class RunMyApp extends StatelessWidget {
RunMyApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) =>
NextPage()));
},
child: Text('Goto Next Page')),
),
);
}
}
class NextPage extends StatelessWidget {
const NextPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('developers Page'),
),
body: Center(
child: Text('5th computer science students'),
),
);
}
}
Output….

5. Gradient to Container Background


import 'package:flutter/material.dart';
void main() {
runApp(RunMyApp());
}
class RunMyApp extends StatelessWidget {
const RunMyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('Gradient Background'),
),
body: Container(
width: double.maxFinite,
height: double.maxFinite,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.green, Color.fromARGB(255, 29, 221, 163)],
),
),
child: Center(child: Text('Set Gradient to Container Background'))),
),
);
}
}

Output….
1. Flutter Text field
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: const MyApp(),
));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
_State createState() => _State();
}

class _State extends State<MyApp> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter TextField Example'),
),
body: Padding(
padding: EdgeInsets.all(15),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(15),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'User Name',
hintText: 'Enter Your Name',
),
),
),
Padding(
padding: EdgeInsets.all(15),
child: TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white, // Text color
backgroundColor: Colors.blue, // Button color
),
child: Text( 'Sign In', style: TextStyle( color: Colors.white), //
Correct way to set text color
),
onPressed: () {},
)
],
)));
}
}
1. Flutter text form field
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'text Form field Styling Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatelessWidget {
const MyCustomForm({super.key});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
),
Padding(padding: const
EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8,
vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your password',
),
),
),
Padding(padding: const EdgeInsets.symmetric(horizontal:
8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your email',
),
),
),
],
);
}
}

Output….
2. Validation of text form field
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());


class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey<FormState> _formKey =
GlobalKey<FormState>();
AutovalidateMode _autoValidate =
AutovalidateMode.disabled;
String? _name;
String? _mobile;
String? _email;
void _validateInputs() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
} else {
setState(() {
_autoValidate = AutovalidateMode.always;
});
}
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Form Validation'),
),
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.all(15.0),
child: Form(
key: _formKey,
autovalidateMode: _autoValidate,
child: formUI(),
),
),
),
),
);
}
Widget formUI() {
return Column(
children: <Widget>[
TextFormField(
decoration: const InputDecoration(labelText:
'Name'),
keyboardType: TextInputType.text,
validator: validateName,
onSaved: (String? val) {
_name = val;
},
),
TextFormField(
decoration: const InputDecoration(labelText:
'Mobile'),
keyboardType: TextInputType.phone,
validator: validateMobile,
onSaved: (String? val) {
_mobile = val;
},
),
TextFormField(
decoration: const InputDecoration(labelText:
'Email'),
keyboardType: TextInputType.emailAddress,
validator: validateEmail,
onSaved: (String? val) {
_email = val;
},
),
const SizedBox(
height: 10.0,
),
OutlinedButton(
onPressed: _validateInputs,
child: const Text('Validate'),
)
],
);
}

String? validateName(String? value) {


if (value!.isEmpty) {
return 'Name cannot be empty';
}
if (value.length < 3) {
return 'Name must be more than 2 charater';
} else {
return null;
}
}
String? validateMobile(String? value) {
if (value!.isEmpty) {
return 'Phone number cannot be empty';
}
if (value.length != 10) {
return 'Mobile Number must be of 10 digit';
} else {
return null;
}
}
String? validateEmail(String? value) {
String pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]
+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.
[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = RegExp(pattern);
if (value!.isEmpty) {
return 'Email cannot be empty';
}
if (!regex.hasMatch(value)) {
return 'Enter Valid Email';
} else {
return null;
}
}
}
Output…..
10. Drop down list
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter DropDownButton example',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() =>
_MyHomePageState();
}
class _MyHomePageState extends
State<MyHomePage> {
// Initial Selected Value
String dropdownvalue = 'departement';
// List of items in our dropdown menu
var items = [
'departement',
'software',
'cs',
'It',
'Is',
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter DropDownButton
example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DropdownButton(
// Initial Value
value: dropdownvalue,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items: items.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
],
),
),
);
}
}
Output…..
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'drop down list example 2',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: const TextTheme(
bodyText1: TextStyle(fontSize: 32),
bodyText2: TextStyle(fontSize: 32),
subtitle1: TextStyle(fontSize: 32),
),
),
debugShowCheckedModeBanner: false,
home: const DropdownListTutorial(),
);
}
}

class DropdownListTutorial extends StatefulWidget {


const DropdownListTutorial({Key? key}) : super(key:
key);
@override
_DropdownListTutorialState createState() =>
_DropdownListTutorialState();
}
class _DropdownListTutorialState extends
State<DropdownListTutorial> {
List<String> items = [
"computer science",
"IT",
"SWE",
"IS",
"cyber security",
"Artificial intellgence"
];
String currentItem = "";
@override
void initState() {
currentItem = items[0];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Dropdown List in flutter
exmple"),
),
body: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Container(
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(10),
),
child: DropdownButton(
alignment: Alignment.topCenter,
borderRadius: BorderRadius.circular(8),
dropdownColor: Colors.blueAccent,
value: currentItem,
items: items
.map<DropdownMenuItem<String>>(
(e) => DropdownMenuItem(
value: e,
child: Text(e),
alignment: Alignment.center,
),
)
.toList(),
onChanged: (String? value) => setState(
() {
if (value != null) currentItem = value;
},
),
),
),
Text(currentItem),
],
),
),
);
}
}
Output….
11. Gradient button
import
'package:flutter/material.dart';
void main() {
runApp(RunMyApp());
}
class RunMyApp extends
StatefulWidget {
const RunMyApp({super.key});

@override
State<RunMyApp> createState()
=> _RunMyAppState();
}
class _RunMyAppState extends
State<RunMyApp> {
@override
Widget build(BuildContext
context) {
return MaterialApp(
debugShowCheckedModeBanner:
false,
theme:
ThemeData(primarySwatch:
Colors.green),
home: Scaffold(
appBar: AppBar(
title: Text('Gradient
Button'),
),
body: Center(
child: Container(
height: 44.0,
decoration:
BoxDecoration(
gradient:
LinearGradient(
colors:
[Color.fromARGB(255, 2, 173,
102), Colors.blue])),
child:
ElevatedButton(
onPressed: () {},
style:
ElevatedButton.styleFrom(

backgroundColor:
Colors.transparent,
shadowColor:
Colors.transparent),
child:
Text('Elevated Button'),
),
),
),
),
);
}
}
Output…
12. Circular button
import
'package:flutter/material.dart';
void main() {
runApp(RunMyApp());
}
class RunMyApp extends
StatefulWidget {
const RunMyApp({super.key});
@override
State<RunMyApp> createState()
=> _RunMyAppState();
}
class _RunMyAppState extends
State<RunMyApp> {
@override
Widget build(BuildContext
context) {
return MaterialApp(
debugShowCheckedModeBanner:
false,
theme:
ThemeData(primarySwatch:
Colors.green),
home: Scaffold(
appBar: AppBar(
title: Text('Gradient
Button'),
),
body: Center(
child: Container(
height: 120.0, //
height of the button
decoration:
BoxDecoration(
shape:
BoxShape.circle, // shape makes
the circular button
gradient:
LinearGradient(// gives the
Gradient color
colors:
[Color.fromARGB(255, 2, 173,
102), Colors.blue])),
child:
ElevatedButton(
onPressed: () {},
style:
ElevatedButton.styleFrom(

backgroundColor:
Colors.transparent,
shadowColor:
Colors.transparent),
child:
Text('Elevated Button'),
),
),
),
),
);
}
}
Output…
13. Demonstration of row and column
import
'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context)
{
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatelessWidget {
Home({super.key});
@override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(
title:
const Text('Demonstration
for Column and Row Button'), // Fixed
typo
backgroundColor:
Colors.green,
),
body: Column(
children: [
const SizedBox(height: 15),
const SizedBox(
height: 20,
child:
Text('Demonstration of Row'),
),
Row(
children: [
Card(
margin: const
EdgeInsets.all(10),
elevation: 8,
child: Container(
padding: const
EdgeInsets.all(25),
child: const Text(
'IT third year',
style:
TextStyle(color: Colors.green),
),
),
),
const SizedBox(width:
2),
Card(
margin: const
EdgeInsets.all(10),
elevation: 8,
child: Container(
padding: const
EdgeInsets.all(25),
child: const Text(
'IT third year',
style:
TextStyle(color: Colors.green),
),
),
),
],
),
const SizedBox(height: 30),
const SizedBox(
height: 20,
child:
Text('Demonstration of Column'),
),
Column(
children: [
Card(
margin: const
EdgeInsets.all(10),
elevation: 8,
child: Container(
padding: const
EdgeInsets.all(25),
child: const Text(
'IT third year',
style:
TextStyle(color: Colors.green),
),
),
),
const SizedBox(height:
4), // Changed from width to height
Card(
margin: const
EdgeInsets.all(10),
elevation: 8,
child: Container(
padding: const
EdgeInsets.all(25),
child: const Text(
'IT third year',
style:
TextStyle(color: Colors.green),
),
),
),
],
)
],
),
);
}
}
Output…
14. Flutter table example
Corrections & Improvements:

✅ Renamed _TableExample to _MyAppState for clarity.


✅ Used const where applicable to improve performance.
✅ Added debugShowCheckedModeBanner: false to MaterialApp to
remove the debug banner.
✅ Ensured all Text widgets inside TableRow use a TextStyle for
consistency.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatefulWidget {


@override

_TableExample createState() => _TableExample();

class _TableExample extends State<MyApp> {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold(

appBar: AppBar(

title: Text('Flutter Table Example'),

),

body: Center(

child: Column(children: <Widget>[

Container(

margin: EdgeInsets.all(20),

child: Table(

defaultColumnWidth: FixedColumnWidth(120.0),

border: TableBorder.all(

color: Colors.black, style: BorderStyle.solid, width: 2),


children: [

TableRow(children: [

Column(children: [

Text('computer science', style: TextStyle(fontSize:


20.0))

]),

Column(children: [

Text('software', style: TextStyle(fontSize: 20.0))

]),

Column(children: [

Text('information technology',

style: TextStyle(fontSize: 20.0))

]),

]),

TableRow(children: [

Column(children: [Text('Javatpoint')]),

Column(children: [Text('Flutter')]),

Column(children: [Text('5*')]),

]),

TableRow(children: [
Column(children: [Text('firebase')]),

Column(children: [Text('MySQL')]),

Column(children: [Text('5*')]),

]),

TableRow(children: [

Column(children: [Text('SQLlite')]),

Column(children: [Text('ReactJS')]),

Column(children: [Text('5*')]),

]),

],

),

),

]))),

);

Output……

15. Flutter table


import
'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

// MyApp as a StatefulWidget
class MyApp extends
StatefulWidget {
const MyApp({super.key});

@override
_MyAppState createState() =>
_MyAppState();
}

class _MyAppState extends


State<MyApp> {
@override
Widget build(BuildContext
context) {
return MaterialApp(

debugShowCheckedModeBanner:
false, // Removes the debug
banner
home: Scaffold(
appBar: AppBar(
title: const
Text('Flutter DataTable
Example'),
),
body: ListView(
children: <Widget>[
const Center(
child: Padding(
padding:
EdgeInsets.all(16.0),
child: Text(
'People-
Chart',
style:
TextStyle(fontSize: 25,
fontWeight: FontWeight.bold),
),
),
),
DataTable(
columnSpacing:
20.0,
headingRowColor:
MaterialStateColor.resolveWith(
(states) =>
Colors.grey.shade300),
border:
TableBorder.all(width: 1, color:
Colors.black54),
columns: const [
DataColumn(
label: Text(
'ID',
style:
TextStyle(fontSize: 18,
fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(
'Name',
style:
TextStyle(fontSize: 18,
fontWeight: FontWeight.bold),
),
),
DataColumn(
label: Text(

'Profession',
style:
TextStyle(fontSize: 18,
fontWeight: FontWeight.bold),
),
),
],
rows: const [
DataRow(cells: [

DataCell(Text('1')),

DataCell(Text('Stephen')),

DataCell(Text('Actor')),
]),
DataRow(cells: [

DataCell(Text('5')),

DataCell(Text('John')),
DataCell(Text('Student')),
]),
DataRow(cells: [

DataCell(Text('10')),

DataCell(Text('Harry')),

DataCell(Text('Leader')),
]),
DataRow(cells: [

DataCell(Text('15')),

DataCell(Text('Peter')),

DataCell(Text('Scientist')),
]),
],
),
],
),
),
);
}
}
Output…..
16. Flutter table 2
import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}

class HomePage extends StatelessWidget {


const HomePage({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[100], //
Background color of scaffold
appBar: AppBar(
title: const Text("Flutter Table"),
backgroundColor: Colors.redAccent,
),
body: Container(
padding: const EdgeInsets.all(15),
child: Table(
border:
TableBorder.all(width: 1, color:
Colors.black45), // Table border
children: const [
TableRow(
decoration: BoxDecoration(color:
Colors.grey),
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: Text("S/N",
style: TextStyle(fontWeight:
FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Name",
style: TextStyle(fontWeight:
FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Address",
style: TextStyle(fontWeight:
FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Nation",
style: TextStyle(fontWeight:
FontWeight.bold)),
),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0),
child: Text("1.")),
Padding(
padding: EdgeInsets.all(8.0), child:
Text("Krishna Karki")),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Nepal, Kathmandu")),
Padding(padding: EdgeInsets.all(8.0),
child: Text("Nepal")),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0),
child: Text("2.")),
Padding(padding: EdgeInsets.all(8.0),
child: Text("John Wick")),
Padding(
padding: EdgeInsets.all(8.0), child:
Text("New York, USA")),
Padding(padding: EdgeInsets.all(8.0),
child: Text("USA")),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0),
child: Text("3.")),
Padding(
padding: EdgeInsets.all(8.0), child:
Text("Fredrick May")),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Berlin, Germany")),
Padding(padding: EdgeInsets.all(8.0),
child: Text("Germany")),
],
),
],
),
),
);
}
}
Output…
17. Flutter table
import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}

class HomePage extends StatelessWidget {


const HomePage({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[100], // Background
color of scaffold
appBar: AppBar(
title: const Text("Flutter Table"),
backgroundColor: Colors.redAccent,
),
body: Container(
padding: const EdgeInsets.all(15),
child: Table(
border: TableBorder.all(width: 1, color:
Colors.black45), // Table border
children: const [
TableRow(
decoration: BoxDecoration(color:
Colors.grey),
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: Text("S/N", style:
TextStyle(fontWeight: FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Name", style:
TextStyle(fontWeight: FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Address", style:
TextStyle(fontWeight: FontWeight.bold)),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text("Nation", style:
TextStyle(fontWeight: FontWeight.bold)),
),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0), child:
Text("1.")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Krishna Karki")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Nepal, Kathmandu")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Nepal")),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0), child:
Text("2.")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("John Wick")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("New York, USA")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("USA")),
],
),
TableRow(
children: [
Padding(padding: EdgeInsets.all(8.0), child:
Text("3.")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Fredrick May")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Berlin, Germany")),
Padding(padding: EdgeInsets.all(8.0), child:
Text("Germany")),
],
),
],
),
),
);
}
}
Output….
Summary of Fixes & Enhancements
1. Proper Widget Naming: _DataTableExample →
_MyAppState for better readability.
2. Added const for Performance: Reduces widget
rebuilds, making the app smoother.
3. Better UI with Padding & Colors: Tables now have
improved spacing and border styling.
4. Consistent TextStyle Usage: Ensured all text inside
tables follows a uniform font size and weight.
5. Fixed Duplicate Flutter Example Issue: Now two
examples are structured properly.
Now your Flutter tables are well-optimized and
formatted correctly!

You might also like