Skip to content
This repository was archived by the owner on Feb 25, 2022. It is now read-only.
This repository was archived by the owner on Feb 25, 2022. It is now read-only.

How to keep state in the "books" example #347

@amitrotner

Description

@amitrotner

Hi,

I am trying to add a state keeping ability to the "books" example.
I have followed https://gorouter.dev/nested-navigation#keeping-state and changed author_list.dart so the authors list will be 50 times longer (just for the demonstration) and added AutomaticKeepAliveClientMixin.

// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:flutter/material.dart';

import '../data.dart';

class AuthorList extends StatefulWidget {
  const AuthorList({
    required this.authors,
    this.onTap,
    Key? key,
  }) : super(key: key);

  final List<Author> authors;
  final ValueChanged<Author>? onTap;

  @override
  State<AuthorList> createState() => _AuthorListState();
}

class _AuthorListState extends State<AuthorList> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      itemCount: widget.authors.length * 50,
      itemBuilder: (context, index) => ListTile(
        title: Text(
          widget.authors[index % widget.authors.length].name,
        ),
        subtitle: Text(
          '${widget.authors[index % widget.authors.length].books.length} books',
        ),
        onTap: widget.onTap != null ? () => widget.onTap!(widget.authors[index % widget.authors.length]) : null,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

However, when I scroll down the authors page, move to another page and return to the authors page, the state is not preserved.

How can I modify this example to enable state preserving?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions