前提・実現したいこと
私は現在Fluterの勉強をしています。
下記のサイトから、TapBoxBというチュートリアルを進めているのですが、上手く動きません。
https://flutter.dev/docs/development/ui/interactive
該当のソースコード
dart
1// main.dart 2import 'package:flutter/material.dart'; 3 4void main() => runApp(MyApp()); 5 6class ParentWidget extends StatefulWidget { 7 8 _ParentWidgetState createState() => _ParentWidgetState(); 9} 10 11class _ParentWidgetState extends State<ParentWidget> { 12 bool _active = false; 13 14 void _handleTapboxChanged(bool newValue) { 15 setState(() { 16 _active = newValue; 17 }); 18 } 19 20 21 Widget build(BuildContext context) { 22 return Container( 23 child: TapboxB( 24 active: _active, 25 onChanged: _handleTapboxChanged, 26 ), 27 ); 28 } 29} 30 31// StatelessWidget継承 32class TapboxB extends StatelessWidget { 33 TapboxB({Key key, this.active: false, this.onChanged}) : super(key: key); 34 35 final bool active; 36 final ValueChanged<bool> onChanged; 37 38 void _handleTap() { 39 onChanged(!active); 40 } 41 42 Widget build(BuildContext context) { 43 return GestureDetector( 44 onTap: _handleTap, 45 child: Container( 46 child: Center( 47 child: Text( 48 active ? 'Active' : 'Inactive', 49 style: TextStyle(fontSize: 32.0, color: Colors.white), 50 ), 51 ), 52 width: 200.0, 53 height: 200.0, 54 decoration: BoxDecoration( 55 color: active ? Colors.lightGreen[700] : Colors.grey[600], 56 ), 57 ), 58 ); 59 } 60} 61 62class MyApp extends StatelessWidget { 63 64 Widget build(BuildContext context) { 65 return MaterialApp( 66 title: 'Flutter Demo', 67 home: Scaffold( 68 appBar: AppBar( 69 title: Text('Flutter Demo'), 70 ), 71 body: Center( 72 child: TapboxB(), 73 ), 74 ), 75 ); 76 } 77}
基本的には参考ページをトレースしています。
問題点
どうやら、boxをタップした時に走る下の部分の onChanged
がnullになってるのが問題のようです。
dart
1// 省略 2class TapboxB extends StatelessWidget { 3 TapboxB({Key key, this.active: false, this.onChanged}) : super(key: key); 4 5 final bool active; 6 final ValueChanged<bool> onChanged; 7 8 void _handleTap() { 9 onChanged(!active); 10 } 11 12 Widget build(BuildContext context) { 13// 省略
このonChangedから_ParentWidgetStateに上手くコールバックを渡すにはどのようにするのがいいでしょうか?
また、参考になるページなどあれば教えて頂けると幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/08/07 05:37
2019/08/07 06:49