想要在任意页面跳转到指定的底部导航栏,需要用到Provider。
- 将下标存放到 Provider 中,
- 将page 和 BottomNavigationBar的 index 绑定
Provider.of(context).currentIndex
,
- 在
onTap(index)
方法中使用Provider.of(context).currentIndex = index
实现点击底部导航栏切换。
- 在其他页面使用
Provider.of(context).currentIndex = 1
,跳转到指定页面。
需要的插件如下:
BottomNavigationBarProvider
bottom_nav_provider.dartimport 'package:flutter/material.dart';
class BottomNavProvider with ChangeNotifier { int _currentIndex = 0;
int get currentIndex => _currentIndex;
set currentIndex(int currentIndex) { _currentIndex = currentIndex; notifyListeners(); }
void setIndex(int index) { currentIndex = index; } }
|
在main.dart中添加providers
main.dartimport 'package:e_book_clone/app.dart'; import 'package:e_book_clone/pages/bottom_nav_provider.dart'; import 'package:e_book_clone/theme/theme_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart';
void main() { runApp( MultiProvider(providers: [ ChangeNotifierProvider(create: (context) => ThemeProvider()), ChangeNotifierProvider(create: (context) => BottomNavProvider()), ], child: const MyAPP()), ); }
|
RootPage
import 'package:e_book_clone/json/root_app_json.dart'; import 'package:e_book_clone/pages/douban_read/douban_read_page.dart'; import 'package:e_book_clone/pages/home/home_page.dart'; import 'package:e_book_clone/pages/my_book/my_book_page.dart'; import 'package:e_book_clone/pages/ebook_store/store_page.dart'; import 'package:e_book_clone/pages/bottom_nav_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_lazy_indexed_stack/flutter_lazy_indexed_stack.dart'; import 'package:provider/provider.dart'; import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';
class RootPage extends StatelessWidget { const RootPage({super.key});
@override Widget build(BuildContext context) { var bg = Theme.of(context).colorScheme.surface; return Scaffold( appBar: AppBar( elevation: 0, toolbarHeight: 0, backgroundColor: bg, surfaceTintColor: bg), backgroundColor: bg, bottomNavigationBar: _getBottomNavigator(context), body: LazyIndexedStack( index: Provider.of<BottomNavProvider>(context).currentIndex, children: const [ HomePage(), DoubanReadPage(), StorePage(), MyBookPage(), ], ), ); }
Widget _getBottomNavigator(BuildContext context) { return SalomonBottomBar( currentIndex: Provider.of<BottomNavProvider>(context).currentIndex, onTap: (index) { Provider.of<BottomNavProvider>(context, listen: false).currentIndex = index; }, items: List.generate( rootAppJson.length, (index) { return SalomonBottomBarItem( selectedColor: Theme.of(context).colorScheme.onSurface, unselectedColor: Theme.of(context).colorScheme.inversePrimary, icon: Icon(rootAppJson[index]['icon']), title: Text(rootAppJson[index]['text']), ); }, ), ); } }
|