简体   繁体   English

Flutter 使用 RiverPod 状态管理更改文本值

[英]Flutter changing Text value using RiverPod State management

In this below code i made simply code to change Text widget string, default string can be shown into Text widget but when i try to click FloatingActionButton is doesn't change.在下面的代码中,我做了简单的代码来更改Text小部件字符串,默认字符串可以显示到Text小部件中,但是当我尝试单击FloatingActionButton不会改变。

clicking on HotReload cause chage it to new value, where i should change to resolve this issue?单击HotReload会导致将其更改为新值,我应该在哪里更改以解决此问题?

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


class MyString extends StateNotifier<String> {
  MyString() : super('Hello World');

  void change(String text) => state = text;
}

final showHello = StateNotifierProvider<MyString>((ref) => MyString());

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('SAMPLE'),
        ),
        body: Center(
          child: Consumer(
            builder: (context, watch, _) {
              final s = watch(showHello).state;
              return Text(s);
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => context.read(showHello).change('Clicked On Button'),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}

April 2021 Update : As of Riverpod >= 0.14.0 the syntax has now been updated (scroll down for original answer). 2021 年 4 月更新:从 Riverpod >= 0.14.0 开始,语法现已更新(向下滚动以获取原始答案)。 The following demonstrates how the example code provided in the question could be converted to the updated syntax:下面演示了如何将问题中提供的示例代码转换为更新的语法:

import 'package:flutter/material.dart';
// Note importing hooks_riverpod/all.dart is now deprecated
import 'package:hooks_riverpod/hooks_riverpod.dart';


class MyString extends StateNotifier<String> {
  MyString() : super('Hello World');

  void change(String text) => state = text;
}

// Note the extra parameter, String, to specify what is provided by the Notifier
final showHello = StateNotifierProvider<MyString, String>((ref) => MyString());

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('SAMPLE'),
        ),
        body: Center(
          child: Consumer(
            builder: (context, watch, _) {
              // Note here, state does not need to be specified.
              final s = watch(showHello);
              return Text(s);
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            // Note that we now specify notifier here to access non-state
            // attributes of the Notifier
            context.read(showHello.notifier).change('Clicked On Button');
          },
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

More on upgrading to Riverpod 0.14.0+ can be found here .可以在此处找到有关升级到 Riverpod 0.14.0+ 的更多信息


The following contains the original answer to the question.以下包含问题的原始答案。 It is only valid for riverpod <= 0.13 .它仅对riverpod <= 0.13有效。

Change:改变:

final s = watch(showHello).state;

to:到:

final s = watch(showHello.state);

The reason for this behavior is that you are watching the notifier itself, not its state.这种行为的原因是您正在观察通知程序本身,而不是它的状态。 Since the notifier object isn't actually being changed, just the state property, a rebuild is not triggered (which is why you see the update upon hot reload).由于实际上并没有更改通知程序对象,只是更改了 state 属性,因此不会触发重建(这就是您在热重载时看到更新的原因)。 By watching the state itself, we rebuild whenever the state changes.通过观察状态本身,我们在状态改变时重建。

This concept extends to other kinds of providers, eg listening to the last exposed value of a StreamProvider .这个概念扩展到其他类型的提供者,例如侦听 StreamProvider 的最后公开值

A similar question I answered in the past. 我以前回答过一个类似的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM