Why we never use global variables to manage state in Flutter

I believe no one uses global variables to manage the state of a Flutter application. Without a doubt, we need state management packages or basic widgets for Flutter, such as InheritedWidget for our StatefulWidget for Flutter apps.

However, do we really understand the value of these packages for state management? What topics must we consider when thinking about state management?

In this article, we'll build a simple counter application intentionally using global variables for state management to explore what happens. This challenge will help us understand what problems state management packages are trying to solve.

Counter application with global variable integer value

We'll start with the simple counter application below.

import 'package:flutter/material.dart';

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

var counter = 0;

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(counter.toString()),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.add),
          onPressed: () {
            counter++;
          },
        ),
      ),
    );
  }
}

It must be a simple counter application, except

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/132471795
Recommended