해결된 질문
작성
·
251
0
class SelectProviderScreen extends ConsumerWidget {
const SelectProviderScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(selectProvider);
return DefaultLayout(
title: 'SelectProviderScreen',
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(state.name),
Text(state.isSpicy.toString()),
Text(state.hasBought.toString()),
ElevatedButton(
onPressed: () {
ref.read(selectProvider.notifier).toggleIsSpicy();
},
child: Text('Spicy Toggle'),
),
ElevatedButton(
onPressed: () {
ref.read(selectProvider.notifier).toggleHasBought();
},
child: Text('hasBought Toggle'),
),
],
),
),
);
}
}
import 'package:advanced_state/model/shopping_item_model.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final selectProvider = StateNotifierProvider<SelectNotifier, ShoppingItemModel>(
(ref) => SelectNotifier(),
);
class SelectNotifier extends StateNotifier<ShoppingItemModel> {
SelectNotifier()
: super(
ShoppingItemModel(
name: '김치',
quantity: 3,
hasBought: false,
isSpicy: true,
),
);
toggleHasBought() {
state.copyWith(
hasBought: !state.hasBought,
);
}
toggleIsSpicy() {
state.copyWith(
isSpicy: !state.isSpicy,
);
}
}
class ShoppingItemModel {
// 이름
final String name;
// 갯수
final int quantity;
// 구매했는지
final bool hasBought;
// 매운지
final bool isSpicy;
ShoppingItemModel({
required this.name,
required this.quantity,
required this.hasBought,
required this.isSpicy,
});
ShoppingItemModel copyWith({ //선택한 값만 선택적으로 변경할 수 있게 메소드를 만든다.
String? name,
int? quantity,
bool? hasBought,
bool? isSpicy,
}) {
return ShoppingItemModel(
name: name ?? this.name, //name이 null일때는 this.name, null이 아닐때는 입력받은 name이 된다.
quantity: quantity ?? this.quantity,
hasBought: hasBought ?? this.hasBought,
isSpicy: isSpicy ?? this.isSpicy,
);
}
}
답변 1
0
아 토글 함수 만들때 state.copyWith( hasBought: !state.hasBought)를 state에 재 할당해주지 않아서 생긴 문제였네요.... 해결했습니다 ㅠㅠ 죄송해요
state = state.copyWith( hasBought: !state.hasBought); 이렇게 해주니 해결되었습니다!