iTranslated by AI
Controlling BottomNavigationBar with flutter_riverpod
I tried it and it worked!
TL;DR
- The code is almost the same as in this article:
- Article on creating a Stateless BottomNavigationBar with Flutter was great, so I tried it | Junya Kitayama | zenn
- And the original article for that:
- Flutter: About creating a simple and Stateless BottomNavigationBar | konbu | note
Create Project via CLI
In your terminal:
flutter create myapp
cd myapp
# Start the iOS simulator if it's not already running
open -a Simulator
# Compile and run. You can also do this immediately after flutter create.
flutter run
Result Image
Final File List
Install Necessary Packages
This time, we will introduce two additional packages.
- pedantic_mono
- A strict linter
- pedantic_mono | pub.dev
- Recommendation for strengthening static analysis in Dart/Flutter. Your project needs analysis_options.yaml… | by mono | Flutter 🇯🇵 | Medium
- A strict linter
- flutter_riverpod
- A state management package
- flutter_riverpod | pub.dev
Configure your pubspec.yaml as follows.
While the formal way is to run flutter pub get after modifying it, the Flutter extension for VSCode will automatically run flutter pub get for you once you save the file.
name: myApp
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
flutter_riverpod: ^0.12.2
dev_dependencies:
pedantic_mono: any
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
Create analysis_options.yaml for pedantic_mono
Prepare analysis_options.yaml in the root directory. This will enable linting.
touch analysis_options.yaml
include: package:pedantic_mono/analysis_options.yaml
Create screens for switching the footer
Here, we'll create screens that simply center an icon.
mkdir -p lib/views/screens
touch lib/views/screens/first_page.dart
touch lib/views/screens/second_paage.dart
import 'package:flutter/material.dart';
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: const Center(
child: const Icon(
Icons.face,
size: 200,
),
),
);
}
}
import 'package:flutter/material.dart';
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(
body: const Center(
child: const Icon(
Icons.fastfood,
size: 200,
),
),
);
}
}
Define a StatelessWidget with BottomNavigationBar
In the previous article, I prepared a Notifier class that inherited ChangeNotifier, but this time I will use Riverpod's StateProvider.
Since it's just a selected value for a tab, there's no need to prepare a dedicated class, so let's just observe the enum directly. Placing the Provider globally is one of the interesting aspects of Riverpod.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final pageTypeProvider = StateProvider<PageType>((ref) => PageType.first);
enum PageType {
first,
second,
}
I wrote the subheading as "Define a StatelessWidget with BottomNavigationBar" and I am indeed writing it that way, but the Riverpod Consumer used under the Widget actually inherits from StatefulWidget, so I'm starting to wonder what exactly I'm trying to achieve here? (That said, since we can delegate and encapsulate state management with Riverpod, the management cost is completely different from using StatefulWidget directly.)
Anyway, the overall code for this part looks like this:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'first_page.dart';
import 'second_paage.dart';
final pageTypeProvider = StateProvider<PageType>((ref) => PageType.first);
enum PageType {
first,
second,
}
class RootPage extends StatelessWidget {
final List<Widget> _pageList = <Widget>[
FirstPage(),
SecondPage(),
];
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
// watch the state
final pageType = watch(pageTypeProvider);
final tabItems = [
const BottomNavigationBarItem(
icon: Icon(Icons.face),
label: '',
),
const BottomNavigationBarItem(
icon: Icon(Icons.fastfood),
label: '',
),
];
return Scaffold(
body: _pageList[pageType.state.index],
bottomNavigationBar: BottomNavigationBar(
currentIndex: pageType.state.index,
onTap: (index) {
// update the state
pageType.state = PageType.values[index];
},
items: tabItems,
),
);
},
);
}
}
You can get the index value of a Dart enum using the index property. Conversely, you can convert an int to an enum by specifying the index in values.
- Enums are now available in Dart | NEWS | INDETAIL Co., Ltd.
- Flutter / Dart Convert Int to Enum | Stack Overflow
- Enumerated types | Language tour | Dart
Create the StatelessWidget for runApp()
Finally, create the view entry point. Wrap the widget in ProviderScope() to monitor the Riverpod Provider.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'views/screens/root_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ProviderScope(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.iOS: FadeUpwardsPageTransitionsBuilder(),
},
),
),
darkTheme: ThemeData(brightness: Brightness.dark),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (_) => RootPage(),
},
),
);
}
}
Once this is done, you should be able to run flutter run and see the screen shown in the "Result Image" above.
Good job!
Here is the repository for this project.
References
- Riverpod
- lohanidamodar/fl_live_launcher: Let's make a android launcher app using Flutter | GitHub
Discussion