#flutter
Managing State
Managing state is key to building dynamic applications. Flutter provides several methods for managing state, from local state management using setState() to global state management solutions like Provider.
Using setState()
setState() is the simplest way to manage state within a widget.
1import 'package:flutter/material.dart';23void main() {4runApp(const MainApp());5}67class MainApp extends StatelessWidget {8const MainApp({super.key});910@override11Widget build(BuildContext context) {12return MaterialApp(13debugShowCheckedModeBanner: false,14initialRoute: '/',15routes: {16'/': (context) => const Home(),17},18);19}20}2122class Home extends StatefulWidget {23const Home({super.key});2425@override26State<Home> createState() => _HomeState();27}2829class _HomeState extends State<Home> {30int _counter = 0;3132// Method to increment counter and update UI33void _incrementCounter() {34setState(() {35_counter++;36});37}3839@override40Widget build(BuildContext context) {41return MaterialApp(42home: Scaffold(43appBar: AppBar(title: const Text('Manage State')),44body: Center(45child: Text(46'Counter: $_counter',47style: const TextStyle(fontSize: 30),48),49),50floatingActionButton: FloatingActionButton(51onPressed: _incrementCounter, // Increment counter on button press52child: const Icon(Icons.add),53),54));55}56}
Key Takeaways
- setState() updates the state of a widget and triggers a rebuild.
- For complex applications, use global state management solutions like Provider or Riverpod.
©2024 Codeblockz
Privacy Policy