flutterで簡単なクイズアプリを作成しているプログラミング初心者です。
ListView内のListTileにお気に入り機能のようなものを付けたいのですが、お気に入り追加を行うために用意したIconButtonを一つ押すとすべてのIconButtonが反応(色が変わる)してしまいます。以下がコードになります。
Dart
1 2class QuizChoice extends StatefulWidget { 3 final String quizCategory; 4 QuizChoice(this.quizCategory); 5 6 7 State<QuizChoice> createState() => _QuizChoice(); 8} 9 10class _QuizChoice extends State<QuizChoice> { 11 bool isVisible = false; 12 bool favorite = false; 13 Set favorite_set = {}; 14 String decision = ""; 15 16 17 Widget build(BuildContext context) { 18 return Scaffold( 19 appBar: AppBar( 20 title: Text(widget.quizCategory), 21 ), 22 body: Stack( 23 children: [ 24 ChangeNotifierProvider( 25 create: (_) => ProductListModel(widget.quizCategory)..getProducts(), 26 child: Consumer<ProductListModel>( 27 builder: (context, model, child) { 28 final products = model.products; 29 return ListView.builder( 30 itemCount: products.length, 31 itemBuilder: (context, index) { 32 return Container( 33 height: 60, 34 decoration: BoxDecoration( 35 border: Border(bottom: BorderSide(color: Colors.teal)), 36 ), 37 child: ListTile( 38 onTap: () { 39 setState(() { 40 isVisible = !isVisible; 41 }); 42 decision = products[index].title; 43 }, 44 leading: IconButton( 45 icon: Icon(Icons.add), 46 onPressed: () { 47 setState(() { 48 favorite = !favorite; 49 }); 50 if (favorite == true) { 51 favorite_set.add(products[index].title); 52 } else { 53 favorite_set.remove(products[index].title); 54 } 55 }, 56 color: favorite ? Colors.purple : Colors.grey, 57 ), 58 trailing: Checkbox( 59 onChanged: print, 60 value: false, 61 ), 62 title: Text( 63 products[index].title, 64 style: TextStyle(fontWeight: FontWeight.bold), 65 ), 66 ), 67 ); 68 }, 69 ); 70 }, 71 ), 72 ), 73 Positioned( 74 bottom: 30, 75 left: 10, 76 right: 10, 77 height: 60, 78 child: Container( 79 child: Visibility( 80 visible: isVisible, 81 child: ElevatedButton( 82 child: Text( 83 "「$decision」クイズにちょうせん!!", 84 style: TextStyle(fontWeight: FontWeight.bold), 85 ), 86 style: ElevatedButton.styleFrom( 87 primary: Colors.purple, 88 onPrimary: Colors.white, 89 shape: const StadiumBorder(), 90 ), 91 onPressed: () { 92 print(favorite_set.length); 93 }, 94 ), 95 ), 96 ), 97 ), 98 ], 99 ), 100 ); 101 } 102}
LIstTileの中でもIconButtonの部分にだけList毎にbool値を持たせたいので、IconButtonだけextractしてみたのですが、親WidgetでSetに値を入れたいのと、パラメータ部分にエラーが出て上手く行きませんでした…。
なにかい良い解決方法はありますでしょうか?
よろしければ力を貸して頂きたいです。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/07/24 12:35