我如何使用 Flutter Riverpod 更改 bool 变量

how can i change bool variable using Flutter Riverpod

我是 Flutter Riverpod management

的新手

我有使用 Flutter Riverpod management 的 stfl 小部件,我需要将测试布尔变量更改为 true 但无法处理它

final testProvider = StateProvider<bool>((ref) => false);

`class FriendsList extends ConsumerStatefulWidget {


  const FriendsList({Key? key}) : super(key: key);

  @override
  _FriendsListState createState() => _FriendsListState();



}

class _FriendsListState extends ConsumerState<FriendsList> {







 @override
 Widget build(BuildContext context) {
 bool test = ref.watch(testProvider);
        return Stack( //edit
    children [
    !test ? Text('bool varible is false')
                         :  Text('bool varible is true')
     FutureBuilder(
           future: FirebaseFirestore.instance.collection('users')
                      .doc('userId').get(),
            builder: (context, AsyncSnapshot snapshot) {
               if(!snapshot.hasData){
                     return Text('');
                  }else{ 
                    
                        ref.read(testProvider.state).state = true;
                   }  
               return snapshot.data['name'];

我不知道该如何处理。我也不确定我的代码是否正确,以及如果需要如何处理它

无法从 Provider 外部更改 Provider 中的值。请改用 StateProvider

看看这个:

final testProvider = StateProvider<bool>((ref) => false);

class FriendList extends ConsumerStatefulWidget {
  const FriendList({Key? key}) : super(key: key);

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _FriendListState();
}

class _FriendListState extends ConsumerState<FriendList> {
  @override
  Widget build(BuildContext context) {
    bool test = ref.watch(testProvider);
    return IconButton(
      onPressed: () {
        ref.read(testProvider.state).state = true;
      },
      icon: Text(
        test ? "Variable updated" : "Still not updated",
      ),
    );
  }
}

访问 Riverpod documentation 了解更多信息。

编辑:我已经使用 ProviderStateNotifierProvider

编写了一个完整的示例

与 Firebase 通信的服务

class UserService {
  static Future<Map> getUser() async {
    DocumentSnapshot<Map> s = await FirebaseFirestore.instance
        .collection('users')
        .doc('userId')
        .get();
    return Map.from(s.data()!);
  }
}

A StateNotifierProviderStateNotifier 正在与服务通信:

final userProvider = StateNotifierProvider<UserNotifier, AsyncValue<Map>>((ref) => UserNotifier());

class UserNotifier extends StateNotifier<AsyncValue<Map>> {
  UserNotifier() : super(AsyncLoading()) {
    get();
  }

  void get() async {
    state = AsyncData(await UserService.getUser());
  }
}

一个testProvider

final testProvider = Provider<bool>((ref) {
  AsyncValue test = ref.watch(userProvider);
  return test is AsyncData;
});

Provider的消费

class FriendList extends ConsumerWidget {
  const FriendList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue value = ref.read(userProvider);
    bool test = ref.read(testProvider);
    return Column(
      children: [
        Text(test ? "bool varialbe is true" : "bool varialbe is false"),
        value.when(
          loading: () => Text('Loading...'),
          data: (data) => Text('${data['name']}'),
          error: (error, __) => Text('Error: $error'),
        ),
      ],
    );
  }
}