Flutter navigationBar与Riverpod

时间:2020-10-19 22:40:21

标签: flutter dart

我尝试管理自己的状态,但我实际上做不到。我想学习如何使用riverpod软件包在管理页面的底部创建导航栏。

我设法管理我们单击的页面,但看不到如何根据所选按钮返回正确的寻呼机

Main.dart:

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:app/ui/screens/my_app/my_app_screen.dart';

void main() {
  runApp(
    const ProviderScope(child: MyApp()),
  );
}

NavigationBarScreen.dart:

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

final provider = StateNotifierProvider((ref) => NavigationNotifier());

class NavigationBarScreen extends HookWidget
{
  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        body : Container(
              margin: EdgeInsets.only(left : 8, right : 8, bottom: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(20), topLeft: Radius.circular(20)),
                boxShadow: [
                  BoxShadow(color: AppColors.colorShadowLight, spreadRadius: 0, blurRadius: 10),
                ],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(50.0),
                child: BottomNavigationBar(
                  type: BottomNavigationBarType.fixed,
                  backgroundColor: AppColors.colorBgDark,
                  fixedColor: AppColors.colorContrastOrange,
                  unselectedItemColor: AppColors.colorFontLight2,
                  currentIndex: 0,
                  showSelectedLabels: false,
                  showUnselectedLabels: false,
                  onTap: context.read(provider).selectPage,
                  items: [
                    BottomNavigationBarItem(
                      icon: Icon(Icons.home),
                      title: Text('Home'),
                    ),
                    BottomNavigationBarItem(
                      icon: Icon(Icons.settings),
                      title: Text('Settings'),
                    ),
                  ],
                ),
              ),
            ),
      ),
    );
  }
}

NavigationNotifier.dart:

import 'package:hooks_riverpod/hooks_riverpod.dart';

enum NavigationBarEvent { HOME, PROFIL}

class NavigationNotifier extends StateNotifier<PageModel> {
  NavigationNotifier() : super(defaultPage);

  static const defaultPage = PageModel(NavigationBarEvent.HOME);

  void selectPage(int i){
    switch (i) {
      case 0:
        state = PageModel(NavigationBarEvent.HOME);
        break;
      case 1:
        state = PageModel(NavigationBarEvent.PROFIL);
        break;
    }
  }
}

class PageModel {
  const PageModel(this.page);
  final NavigationBarEvent page;
}

1 个答案:

答案 0 :(得分:4)

当用户单击底部栏时,似乎已经实现了用于修改状态的所有逻辑。

剩下的唯一一点就是听状态(可能在您的脚手架中),并决定显示哪个页面。

一种可能是写:

true