実現したいこと
Dialog上のTextFieldに値が入っていない場合は、ボタンが無効。TextFieldに値が入っている場合は、ボタンが有効。
コードの説明
isButtonActiveが判定に使用しているフィールドです。
コード
以下が私のコードです。解決方法を教えていただけると有難いです。よろしくお願いいたします。
dart
1import 'package:flutter/cupertino.dart'; 2import 'package:flutter/material.dart'; 3 4void main() => runApp(const MyApp()); 5 6class MyApp extends StatelessWidget { 7 const MyApp({Key? key}) : super(key: key); 8 9 10 Widget build(BuildContext context) { 11 return MaterialApp( 12 home: Scaffold( 13 body: const Center( 14 child: MyStatefulWidget(), 15 ), 16 ), 17 ); 18 } 19} 20 21class MyStatefulWidget extends StatefulWidget { 22 const MyStatefulWidget({Key? key}) : super(key: key); 23 24 25 State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); 26} 27 28class _MyStatefulWidgetState extends State<MyStatefulWidget> { 29 30 // Flag 31 bool isButtonActive = true; 32 // Controller 33 TextEditingController controller = TextEditingController(); 34 35 36 void initState() { 37 super.initState(); 38 39 controller.addListener(() { 40 final isButtonActive = controller.text.isNotEmpty; 41 setState(() => this.isButtonActive = isButtonActive); 42 print( 43 "initState : Controller => ${controller.text} , bool => ${isButtonActive}"); 44 }); 45 } 46 47 48 void dispose() { 49 controller.dispose(); 50 super.dispose(); 51 } 52 53 54 Widget build(BuildContext context) { 55 return Scaffold( 56 body: Center( 57 child: ElevatedButton( 58 child: Text('Button'), 59 onPressed: () { 60 openDialog(); 61 }, 62 ), 63 ), 64 ); 65 } 66 67 Future openDialog() => showDialog( 68 context: context, 69 builder: (context) { 70 return StatefulBuilder( 71 builder: (context, setState) { 72 return AlertDialog( 73 shape: RoundedRectangleBorder( 74 borderRadius: BorderRadius.all(Radius.circular(0))), 75 titlePadding: EdgeInsets.all(0.0), 76 title: Container( 77 padding: EdgeInsets.all(8.0), 78 color: Colors.blue, 79 child: Row( 80 mainAxisAlignment: MainAxisAlignment.center, 81 children: [Text("Title", style: TextStyle(color: Colors.white))], 82 ), 83 ), 84 content: Column( 85 mainAxisSize: MainAxisSize.min, 86 mainAxisAlignment: MainAxisAlignment.start, 87 crossAxisAlignment: CrossAxisAlignment.start, 88 children: [ 89 Text("URL"), 90 Container( 91 width: 400, 92 child: TextField( 93 /// Controller 94 controller: controller, 95 autofocus: true, 96 ), 97 ), 98 ], 99 ), 100 actions: [ 101 ElevatedButton( 102 onPressed: isButtonActive 103 ? () => {setState(() => isButtonActive = false)} 104 : null, 105 child: Text("SEND")), 106 ], 107 ); 108 }, 109 ); 110 }).then((value) => setState(() {})); 111} 112
イメージ画像

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/26 07:45