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

时间:2020-10-13 18:51:10

标签: flutter riverpod

在下面的这段代码中,我简单地编写了更改Text小部件字符串的代码,默认字符串可以显示在Text小部件中,但是当我尝试单击FloatingActionButton时,它不变。

单击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.
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:2)

更改:

final s = watch(showHello).state;

收件人:

final s = watch(showHello.state);

此行为的原因是您正在查看通知程序本身,而不是其状态。由于notifier对象实际上并未更改,仅是state属性,因此不会触发重建(这就是为什么您在热重载时看到更新)的原因。通过观察状态本身,我们可以在状态更改时进行重建。

此概念扩展到其他类型的提供者,例如listening to the last exposed value of a StreamProvider

A similar question I answered in the past.