iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥏

Controlling BottomNavigationBar with flutter_riverpod

に公開

I tried it and it worked!

TL;DR

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.

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.

pubspec.yaml
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
analysis_options.yaml
include: package:pedantic_mono/analysis_options.yaml

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
lib/views/screens/first_page.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,
        ),
      ),
    );
  }
}
lib/views/screens/second_paage.dart
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:

lib/views/screens/root_page.dart
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.

Create the StatelessWidget for runApp()

Finally, create the view entry point. Wrap the widget in ProviderScope() to monitor the Riverpod Provider.

lib/main.dart
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.
https://github.com/JUNKI555/flutter_practice07

References

Discussion