1
0
mirror of https://github.com/flutter/samples.git synced 2026-07-01 18:47:32 +00:00
Files
samples/navigation_and_routing/lib/src/screens/books.dart
Sherzod 3c112d0efc Fix TabController index update (#2753)
Hi, I noticed this bug in the navigation_and_routing sample. 

This PR fixes the tab controller state update issue in BooksScreen.
2025-12-17 11:26:12 -06:00

70 lines
1.7 KiB
Dart

// 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';
class BooksScreen extends StatefulWidget {
final Widget child;
final ValueChanged<int> onTap;
final int selectedIndex;
const BooksScreen({
required this.child,
required this.onTap,
required this.selectedIndex,
super.key,
});
@override
State<BooksScreen> createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this)
..addListener(_handleTabIndexChanged);
}
@override
void didUpdateWidget(covariant BooksScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectedIndex != widget.selectedIndex) {
_tabController.index = widget.selectedIndex;
}
}
@override
void dispose() {
_tabController.removeListener(_handleTabIndexChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Books'),
bottom: TabBar(
controller: _tabController,
tabs: const [
Tab(text: 'Popular', icon: Icon(Icons.people)),
Tab(text: 'New', icon: Icon(Icons.new_releases)),
Tab(text: 'All', icon: Icon(Icons.list)),
],
),
),
body: widget.child,
);
}
void _handleTabIndexChanged() {
widget.onTap(_tabController.index);
}
}