重新打开应用程序后,Flutter应用程序不保留在应用程序中所做的设置

时间:2019-12-23 06:43:08

标签: android flutter dart

我有一个带有两个标签的应用。其中之一是“保存的项目”标签。当我保存项目(从“所有项目列表”的其他屏幕)保存时,即使切换选项卡也能正常工作。但是,当我关闭应用程序并重新打开它时,“保存的项目”列表为空,我必须再次选择项目。我使用了AutomaticKeepAliveClientMixin,但没有帮助。关于如何解决这些人的想法吗?

我的代码:

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return MaterialApp(
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primaryColor: Colors.blue,
    accentColor: Colors.white,
  ),
  home: DefaultTabController(
    length: 2,
    child: Scaffold(
      drawer: Drawer(),
      backgroundColor: Colors.blueAccent,
      appBar: AppBar(
        backgroundColor: Colors.blueAccent,
        title: Text('AIO'),
        bottom: TabBar(
          tabs: <Widget>[
            Tab(icon: Icon(Icons.search)),
            Tab(icon: Icon(Icons.favorite)),
          ],
        ),
      ),
      body: TabBarView(
        children: <Widget>[
          gridView,
          SecondPage(),
        ],
      ),
    ),
  ),
);
}

@override
bool get wantKeepAlive => true;
}

SecondTab代码:

Set<int> favorites = {};

class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> 
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Stack(
  fit: StackFit.expand,
  children: <Widget>[
    _getFavoriteList(),
    Align(
      alignment: Alignment.bottomRight,
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: FloatingActionButton(
          child: Icon(
            Icons.add,
            color: Colors.blue,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => EditFavorites(),
              ),
            ).then((updatedFavorites) {
              if (updatedFavorites != null)
                // setState(() {
                  favorites = updatedFavorites;
                // });
            });
          },
        ),
      ),
    )
  ],
 );
 }

2 个答案:

答案 0 :(得分:0)

AutomaticKeepAliveClientMixin用于在应用程序运行时保留数据,您需要在选项卡,页面等之间切换时保留数据。
我建议您使用SharedPreferences轻松地将数据保存到内存中,以便在再次启动该应用程序时可以将其检索。
SharedPreferenceshttps://pub.dev/packages/shared_preferences

答案 1 :(得分:0)

pubspec.yaml中添加shared_preferences依赖项

更新您的main()

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences pref = await SharedPreferences.getInstance();
  pref.getStringList("favorites")?.forEach((fav){
    favorites.add(int.tryParse(fav));
  });
  runApp(MyApp());
}

然后更新您的SecondPage

Set<int> favorites = {};

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  Future<void> _upDateFavorites(Set<int> updatedFavorites) async {
    print("secong: u$updatedFavorites");
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<String> favoritesAsString =
    updatedFavorites.map((fav) => fav.toString()).toList(); //TODO: Change `favorites`  to `updatedFavorites`
    print(favoritesAsString);
    await pref.setStringList("favorites", favoritesAsString);  //TODO: await here to store it completely
    favorites = updatedFavorites;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: <Widget>[
        _getFavoriteList(),
        Align(
          alignment: Alignment.bottomRight,
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: FloatingActionButton(
              child: Icon(
                Icons.add,
                color: Colors.blue,
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => EditFavorites(),
                  ),
                ).then((updatedFavorites) async {
                  if (updatedFavorites != null)
                    // setState(() {
                    _upDateFavorites(updatedFavorites);
                  // });
                });
              },
            ),
          ),
        )
      ],
    );
  }

  Widget _getFavoriteList() {
    if (favorites?.isNotEmpty == true)
      return _FavoriteList();
    else
      return _EmptyFavoriteList();
  }
}

请不要忘记在import 'package:shared_preferences/shared_preferences.dart';使用SharedPreferences的地方

如果需要重建,请避免将其存储在容器中。

因此删除var favGridView = GridView.builder( ....

class _FavoriteList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      itemCount: favorites.length,
      gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
      itemBuilder: (BuildContext context, int index) {
        print("kkkkkkkkkkk: ${favorites.elementAt(index)}");
        return InkWell(
          child: Card(
            elevation: 10,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(10),
                  child: Container(
                    child: Image.asset(
                        'lib/images/${images[favorites.elementAt(index)]}'), //TODO: Change this
                    // child: SizedBox(child: Text('yashjha'),),
                    // decoration: BoxDecoration(
                    //   image: DecorationImage(
                    //     image: AssetImage('lib/images/${images[index]}'),
                    //     fit: BoxFit.fitWidth,
                    //     alignment: Alignment.topCenter,
                    //   ),
                    // ),
                  ),
                ),
                Text(nameOfSite[favorites.elementAt(index)]), //TODO: Change This
              ],
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => Text("dsadsa")),
            );
          },
        );
      },
    );
  }
}

我还建议使用actions代替FloatingButton中的_EditFavoritesState。因为浮动按钮隐藏了最后一项。这使得它无法添加到收藏夹