Created with <3 with dartpad.dev.
Last active
January 4, 2024 12:11
-
-
Save timelessfusionapps/0ba2a3aaf3fb2d0d4209dd5764274b72 to your computer and use it in GitHub Desktop.
Counter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file | |
// for details. All rights reserved. Use of this source code is governed by a | |
// BSD-style license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), | |
useMaterial3: true, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
const MyHomePage({ | |
Key? key, | |
required this.title, | |
}) : super(key: key); | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
// Using 'int' to represent whole numbers (e.g., count of items) | |
int itemCount = 0; | |
// Using 'double' for precise calculations (e.g., item price) | |
double itemPrice = 5.99; | |
// Using 'num' for flexibility (e.g., total cost may include whole and fractional parts) | |
num totalCost = 0; | |
void _incrementCounter() { | |
// Increment the item count when the button is pressed | |
setState(() { | |
itemCount++; | |
// Calculate the total cost using 'num' | |
totalCost = itemCount * itemPrice; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Counter App'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text( | |
'Item Count: $itemCount', | |
style: TextStyle(fontSize: 20), | |
), | |
SizedBox(height: 20), | |
Text( | |
'Total Cost: \$${totalCost.toStringAsFixed(2)}', | |
style: TextStyle(fontSize: 20), | |
), | |
SizedBox(height: 20), | |
ElevatedButton( | |
onPressed: () { | |
_incrementCounter(); | |
}, | |
child: Text('Add Item'), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment