Flutter Increment Counter Example
Here is an example of how to implement a counter and increment it using Flutter:
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Increment Counter'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Counter:',
style: TextStyle(fontSize: 20),
),
Text(
'$_counter',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
),
),
),
);
}
}
The above code demonstrates a basic example of a Flutter application with a counter that gets incremented when a button is pressed.
The main.dart file contains the main function that runs the application, and a MyApp class that extends StatefulWidget. This makes the app stateful so we can change the counter value dynamically.
Inside the _MyAppState class, we define an integer variable called _counter to hold the count value. The _incrementCounter function is responsible for incrementing the _counter value each time the button is pressed. We use the setState() method to notify Flutter that the state has changed and the UI needs to be updated.
In the build() method, we create the user interface using various Flutter widgets. The Scaffold widget provides a basic layout structure with an AppBar and a body. The Text widget displays the current counter value, while the ElevatedButton triggers the _incrementCounter function when pressed.
- Flutter image.network headers
- Flutter formstate get values
- Flutter form clear validation
- Flutter gesturedetector pass through
- Flutter get safe area height
- Flutter expanded border
- Flutter image picker resize
- Flutter handshakeexception handshake error in client (os error certificate_verify_failed
- Flutter import alias