0

my question is about global variables. I think I have never seen variables declared outside of classes. My question is: why?

For my small projects I often created variables simply like that:

import 'package:flutter/material.dart';

String title = 'this is title';
String userName = '';

StatefulWidget...

It always worked for me to easy use them

helloitsme3
  • 259
  • 3
  • 13
  • It is purely opinion and style. A lot of people who have worked in software for a considerable amount of time have found that this type of declaration can lead to a number of issues, especially on larger projects. Therefore, it is generally discouraged. – eimmer Oct 12 '21 at 18:16

2 Answers2

2

Because normally global parameters are mostly used for constants.

Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program

Are global variables bad?

As for where to put constants, there are few sugestions: What's the best practice to keep all the constants in Flutter?

Adelina
  • 10,915
  • 1
  • 38
  • 46
0

Create Constant.dart file and set all variable to call globally like below,

// string
final title = 'this is title';
// image
final backButton = new AssetImage("assets/arrowLeft.png");

Import the package/path of constant file to file which need to use,

import 'package:projectName/Helper/Common.dart';

Finally, call the variable or any image/constant name,

image: DecorationImage(
       image:backButton,// here is global constant name..
       fit:BoxFit.cover
   ),
AzeTech
  • 623
  • 11
  • 21