Flutter Globals losing their value

E.B*_*ord 5 global-variables dart flutter

Okay, I am sure this is probably an easy to answer question, but after much searching I can't put my finger on the solution.

How does one in Flutter/Dart create a variable in app XYZ that maintains its' value during the time a user moves away from the app, uses another app, allows the phone to go to sleep, etc., then opens the XYZ app again.

I've created a tiny little app that demonstrates the issue as shown below.

The static variable Globals.UID can be incremented upwards, but if the app is moved away from (what term describes using another app correctly?) then as noted the phone goes to sleep, when the user comes back to the app the Globals.UID variable is reset back to -1.

Sometimes the reset is not immediate and I have to let the IOS phone sleep for perhaps 5 minutes to recreate the behavior.

Basically I need Globals.UID to retain its' value until the app is actually exited.

Any insight would truly be appreciated.

import 'package:flutter/material.dart';

import 'package:test_flutter/Globals.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;

      Globals.UID ++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            Text ( "Global variable is:")
            , Text ( Globals.UID.toString() )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

And in a different file called Globals.dart

class Globals {

  static int    UID = -1;
}
Run Code Online (Sandbox Code Playgroud)

Thank you!

Hem*_*Raj 0

实际上,当您不引用引用时,就会发生这种情况。这是一个已知问题,已经修复,可能还没有落地。您可以在此处检查该问题。

请尝试import package_name/globals.dart而不是仅仅import globals.dart如果您正在这样做。

希望有帮助!