更改视图后保留变量值

时间:2019-09-14 08:03:46

标签: flutter

在我的应用程序中,我需要暂时保留一个值(直到应用程序关闭),即变量从null开始,然后被更新,然后用户导航到另一个视图并返回,并且变量仍然具有更新的值值。

我可以从子窗口小部件中的用户交互中获取要更新的变量,但是当用户更改选项卡或将某些内容推入堆栈时,我无法使其保持不变

 LatLng mapPosition;
  double zoomLevel;

 _updateMapState(LatLng position, double zoom) {

    setState(() {
      mapPosition = position;
      zoomLevel = zoom;
    });
  }

我是新手,我不确定我应该找什么。

2 个答案:

答案 0 :(得分:0)

我认为问题是页面/屏幕小部件保留了该值,但是当用户切换选项卡时该小部件被删除了。

Medium article关于在切换页面或标签时如何保留它们。

基本上,您需要给每个页面一个PageStorageKey,并使用一个PageStorage小部件和一个PageStorageBucket

此代码段可能会有所帮助(摘自文章):

import 'package:flutter/material.dart';
import 'first_page.dart';
import 'second_page.dart';

class BottomNavigationBarController extends StatefulWidget {
  @override
  _BottomNavigationBarControllerState createState() =>
      _BottomNavigationBarControllerState();
}

class _BottomNavigationBarControllerState
    extends State<BottomNavigationBarController> {
  final List<Widget> pages = [
    FirstPage(
      key: PageStorageKey('Page1'),
    ),
    SecondPage(
      key: PageStorageKey('Page2'),
    ),
  ];

  final PageStorageBucket bucket = PageStorageBucket();

  int _selectedIndex = 0;

  Widget _bottomNavigationBar(int selectedIndex) => BottomNavigationBar(
        onTap: (int index) => setState(() => _selectedIndex = index),
        currentIndex: selectedIndex,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: Icon(Icons.add), title: Text('First Page')),
          BottomNavigationBarItem(
              icon: Icon(Icons.list), title: Text('Second Page')),
        ],
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
      body: PageStorage(
        child: pages[_selectedIndex],
        bucket: bucket,
      ),
    );
  }
}

答案 1 :(得分:0)

您可以做的一个简单方法是将变量设为全局 main.dart 文件并在您使用该变量的任何地方导入此文件,但唯一的问题是您应该确保它不为空.

double zoomLevel; // in top of the main.dart