首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用“`Notifier`”时不更新UI

使用“`Notifier`”时不更新UI
EN

Stack Overflow用户
提问于 2022-11-08 14:52:10
回答 1查看 45关注 0票数 1

我基本上有一个四页的示例应用程序,我刚刚开始,我开发了一个自定义的底部导航栏。但是,当我切换页面(使用PageView和Riverpod)或点击BlurBottomNav按钮时,它会更改页面,但是BlurBottomNav UI不会更新。我正在使用flutter_riverpod: ^2.1.1

我试过的-

我已尝试将Notifier从无状态转换为消费者,并将ref.watch转换为

  • ,我尝试了StateNotifier而不是

更新:同一代码在ChangeNotifierChangeNotifierProvider一起使用时工作,但对Notifier不起作用

这里有一些片段

pageview_widget.dart

代码语言:javascript
复制
import 'package:demo/src/constants/nav_items.dart';
import 'package:demo/src/features/categories/presentation/categories_page.dart';
import 'package:demo/src/features/favourites/presentation/fav_page.dart';
import 'package:demo/src/features/pageview/data/pageview_service.dart';
import 'package:demo/src/features/pageview/presentation/bottom_nav/bottom_nav.dart';
import 'package:demo/src/features/settings/presentation/settings_page.dart';
import 'package:demo/src/features/wallpaper/presentation/wall_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class PageViewWidget extends StatefulWidget {
  const PageViewWidget({super.key});

  @override
  State<PageViewWidget> createState() => _PageViewWidgetState();
}

class _PageViewWidgetState extends State<PageViewWidget> {
  final pageController = PageController(initialPage: 0);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Breezy'),
        ),
        body: Consumer(
          builder: (context, ref, child) {
            final pageviewService = ref.watch(pageviewServiceProvider.notifier);
            final pageviewServiceRead = ref.watch(pageviewServiceProvider);
            return Stack(
              children: [
                PageView.builder(
                    itemCount: 4,
                    controller: pageController,
                    onPageChanged: (int index) {
                      pageviewService.onPageChanged(index);
                      // pageviewService.changeShowBNB(true);
                    },
                    itemBuilder: (context, index) {
                      switch (index) {
                        case 0:
                          return const WallpaperList();
                        case 1:
                          return const CategoriesPage();
                        case 2:
                          return const FavouritesPage();
                        case 3:
                          return const SettingsPage();
                        default:
                          // Should never get hit.
                          return CircularProgressIndicator(
                            color: Theme.of(context).primaryColor,
                          );
                      }
                    }),
                Positioned.fill(
                  bottom: 20,
                  child: SafeArea(
                    child: BlurBottomNav(
                      onItemSelected: (int value) {
                        pageviewService.onTapByBnb(value, pageController);
                      },
                      selectedIndex: pageviewServiceRead.currentindex,
                      items: navItems,
                    ),
                  ),
                ),
              ],
            );
          },
        ));
  }
}

这是pageview_service.dart

代码语言:javascript
复制
import 'package:demo/src/features/pageview/domain/pageview_navigation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class PageViewService extends Notifier<PageViewNavigation> {
  @override
  PageViewNavigation build() {
    return PageViewNavigation(
        currentindex: 0, changedByBNB: false, showBNB: true);
  }

  void changeShowBNB(bool value) {
    state.showBNB = value;
  }

  void changeIndex(int index) {
    state.currentindex = index;
  }

  void _changeBNBBool(bool value) {
    state.changedByBNB = value;
  }

  void onPageChanged(int index) {
    if ((index != state.currentindex) && (!state.changedByBNB)) {
      changeIndex(index);
    } else {
      _changeBNBBool(false);
    }
  }

  void onTapByBnb(int index, PageController pageController) {
    if (index != state.currentindex) {
      if (pageController.hasClients) {
        _changeBNBBool(true);
        changeIndex(index);
        pageController.animateToPage(
          index,
          curve: Curves.fastOutSlowIn,
          duration: const Duration(milliseconds: 350),
        );
      }
    }
  }
}

final pageviewServiceProvider =
    NotifierProvider<PageViewService, PageViewNavigation>(PageViewService.new);

这是bottom_nav.dart

代码语言:javascript
复制
import 'dart:ui';

import 'package:demo/src/features/pageview/domain/nav_button.dart';
import 'package:demo/src/features/pageview/presentation/bottom_nav/nav_buttons.dart';
import 'package:flutter/material.dart';

class BlurBottomNav extends StatelessWidget {
  final List<BottomNavBarItem> items;
  final ValueChanged<int> onItemSelected;
  final int selectedIndex;
  const BlurBottomNav({
    super.key,
    required this.items,
    required this.onItemSelected,
    required this.selectedIndex,
  });

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: SizedBox(
        width: MediaQuery.of(context).size.width * 0.65,
        height: 57,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(15),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: Container(
              height: 100,
              color: Colors.red,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: items.map((item) {
                    var index = items.indexOf(item);
                    return GestureDetector(
                      onTap: () => onItemSelected(index),
                      child: NavButton(
                        item: item,
                        isSelected: index == selectedIndex,
                      ),
                    );
                  }).toList(),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

这是bottom_nav_button.dart

代码语言:javascript
复制
import 'dart:ui';

import 'package:demo/src/features/pageview/domain/nav_button.dart';
import 'package:flutter/material.dart';

class NavButton extends StatelessWidget {
  final BottomNavBarItem item;
  final bool isSelected;
  const NavButton({
    super.key,
    required this.item,
    required this.isSelected,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(15),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              height: 100,
              width: 43,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                border: Border.all(
                  color: Colors.purple,
                  width: 2,
                ),
                color: isSelected ? item.activeIconColor : Colors.white,
              ),
              child: item.icon,
            ),
          ),
        ),
      ],
    );
  }
}

最后是BottomNavBarItem

代码语言:javascript
复制
import 'package:flutter/material.dart';

class BottomNavBarItem {
  BottomNavBarItem({
    required this.icon,
    required this.activeIconColor,
  });

  final Widget icon;
  final Color activeIconColor;
}

我已经有一段时间没用颤音了,所以请对我温柔点

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-08 17:44:53

请记住,您不能在Notifier子类中使用这样的可变状态:

代码语言:javascript
复制
state.showBNB = value;

相反,它应该是:

代码语言:javascript
复制
state = /* new state */

如果您有一个自定义状态类,请确保所有属性都是final,并添加一个copyWith方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74362721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档