質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Flutter

Flutterは、iOSとAndroidのアプリを同じコードで開発するためのフレームワークです。オープンソースで開発言語はDart。双方のプラットフォームにおける高度な実行パフォーマンスと開発効率を提供することを目的としています。

関数

関数(ファンクション・メソッド・サブルーチンとも呼ばれる)は、はプログラムのコードの一部であり、ある特定のタスクを処理するように設計されたものです。

Dart

Dartは、Googleによって開発されたJavaScriptの代替となることを目的に作られた、ウェブ向けのプログラミング言語である。

Q&A

解決済

1回答

824閲覧

Stateウィジェットの関数をStatelessウィジェットで使いたい

sugoroku

総合スコア5

Flutter

Flutterは、iOSとAndroidのアプリを同じコードで開発するためのフレームワークです。オープンソースで開発言語はDart。双方のプラットフォームにおける高度な実行パフォーマンスと開発効率を提供することを目的としています。

関数

関数(ファンクション・メソッド・サブルーチンとも呼ばれる)は、はプログラムのコードの一部であり、ある特定のタスクを処理するように設計されたものです。

Dart

Dartは、Googleによって開発されたJavaScriptの代替となることを目的に作られた、ウェブ向けのプログラミング言語である。

0グッド

0クリップ

投稿2021/03/21 07:34

編集2021/03/22 09:06

前提・実現したいこと

Stateウィジェットの関数をStatelessウィジェットで使いたいです。
Stateウィジェットにある_saveFileという関数(140行目)をStatelessウィジェット(199行目)で用いたいです。

発生している問題・エラーメッセージ

199行目(一番下の方の所)のonPressedでボタンが押されたときに、function(function:_saveFile)が作動されるようにしたいです。ボタンを押すことはできますが、その後何も起こりません。

エラーメッセージはありません。

該当のソースコード

dart

1import 'dart:io'; 2import 'package:camera/camera.dart'; 3import 'package:flutter/cupertino.dart'; 4import 'package:flutter/material.dart'; 5import 'dart:async'; 6import 'package:flutter_file_dialog/flutter_file_dialog.dart'; 7import 'package:flutter/services.dart'; 8 9 10class TakePictureScreen extends StatefulWidget { 11 12 final CameraDescription camera; 13 14 const TakePictureScreen({ 15 Key key, 16 this.camera, 17 }) : super(key: key); 18 19 20 TakePictureScreenState createState() => TakePictureScreenState(); 21} 22 23class TakePictureScreenState extends State<TakePictureScreen> { 24 CameraController _controller; 25 Future<void> _initializeControllerFuture; 26 27 28 void initState() { 29 super.initState(); 30 // To display the current output from the Camera, 31 // create a CameraController. 32 _controller = CameraController( 33 // Get a specific camera from the list of available cameras. 34 widget.camera, 35 // Define the resolution to use. 36 ResolutionPreset.medium, 37 ); 38 39 // Next, initialize the controller. This returns a Future. 40 _initializeControllerFuture = _controller.initialize(); 41 } 42 43 44 void dispose() { 45 // Dispose of the controller when the widget is disposed. 46 _controller.dispose(); 47 super.dispose(); 48 } 49 50Widget _buildControlBar() { 51 return Row( 52 mainAxisAlignment: MainAxisAlignment.spaceAround, 53 children: <Widget>[ 54 IconButton( 55 color: Colors.white, 56 icon: Icon(Icons.flash_auto), 57 onPressed: () {}, 58 ), 59 FloatingActionButton ( 60 child: Icon(Icons.camera_alt), 61 // Provide an onPressed callback. 62 onPressed: () async { 63 // Take the Picture in a try / catch block. If anything goes wrong, 64 // catch the error. 65 try { 66 // Ensure that the camera is initialized. 67 await _initializeControllerFuture; 68 69 // Attempt to take a picture and get the file `image` 70 // where it was saved. 71 final image = await _controller.takePicture(); 72 73 // If the picture was taken, display it on a new screen. 74 Navigator.push( 75 context, 76 MaterialPageRoute( 77 builder: (context) => DisplayPictureScreen( 78 function:_saveFile, 79 imagePath: image?.path, 80 81 ), 82 ), 83 ); 84 } catch (e) { 85 // If an error occurs, log the error to the console. 86 print(e); 87 } 88 }, 89 ), 90 IconButton( 91 color: Colors.white, 92 icon: Icon(Icons.switch_camera), 93 onPressed:(){} 94 ), 95 ], 96 ); 97 } 98 99 100 Widget build(BuildContext context) { 101 return Scaffold( 102 appBar: AppBar(title: Text('Take a picture')), 103 // Wait until the controller is initialized before displaying the 104 // camera preview. Use a FutureBuilder to display a loading spinner 105 // until the controller has finished initializing. 106body: Stack( 107 children: <Widget>[ 108 FutureBuilder<void>( 109 future: _initializeControllerFuture, 110 builder: (context, snapshot) { 111 if (snapshot.connectionState == ConnectionState.done) { 112 return CameraPreview(_controller); 113 } else { 114 return Center(child: CircularProgressIndicator()); 115 } 116 }, 117 ), 118 Column( 119 mainAxisAlignment: MainAxisAlignment.end, 120 children: <Widget>[ 121 122 _buildControlBar(), 123 Container( 124 padding: EdgeInsets.symmetric(vertical: 10.0), 125 child: Text( 126 'Tap for photo', 127 style: Theme.of(context) 128 .textTheme 129 .subtitle1 130 .copyWith(color: Colors.white), 131 ), 132 ) 133 ], 134 ), 135 ], 136), 137 138 ); 139 } 140Future<void> _saveFile(bool useData) async { 141 String result; 142 String imagePath; 143 String image; 144 bool _isBusy = false; 145 OpenFileDialogType _dialogType = OpenFileDialogType.image; 146 147 SourceType _sourceType = SourceType.photoLibrary; 148 bool _allowEditing = false; 149 File _currentFile; 150 String _savedFilePath; 151 bool _localOnly = false; 152 try { 153 setState(() { 154 _isBusy = true; 155 if(imagePath!=null){ 156 _currentFile = File(imagePath); 157 }else{ 158 _currentFile=null; 159 } 160 161 }); 162 final data = useData ? await _currentFile.readAsBytes() : null; 163 final params = SaveFileDialogParams( 164 sourceFilePath: useData ? null : _currentFile.path, 165 data: data, 166 localOnly: _localOnly, 167 fileName: useData ? "untitled" : null); 168 result= await FlutterFileDialog.saveFile(params: params); 169 print(result); 170 } on PlatformException catch (e) { 171 print(e); 172 } finally { 173 setState(() { 174 _savedFilePath = result ?? _savedFilePath; 175 _isBusy = false; 176 }); 177 } 178 } 179 180} 181 182// A widget that displays the picture taken by the user. 183class DisplayPictureScreen extends StatelessWidget { 184 final String imagePath; 185 final Function function; 186 final String image; 187 DisplayPictureScreen({Key key, this.imagePath,this.function,this.image}) : super(key: key); 188 189 190 Widget build(BuildContext context) { 191 return Scaffold( 192 appBar: AppBar(title: Text('Display the Picture')), 193 // The image is stored as a file on the device. Use the `Image.file` 194 // constructor with the given path to display the image. 195 body: Image.file(File(imagePath)), 196 197 198 floatingActionButton:FloatingActionButton( 199 onPressed:imagePath==null?null :function(false), 200 child:Text('save'), 201 202 203 ), 204 205 ); 206 } 207 208 209 210 211 212} 213 214

試したこと

このサイトを見て、異なるウィジェット間の関数引き渡しをしてみましたがうまくいきませんでした。
具体的には、185行目のFunction function;と78行目のfunction:_saveFileを用いて関数の引き渡しを行っています。

補足情報(FW/ツールのバージョンなど)

pubspec.yamlのdependencies:
cupertino_icons: ^1.0.0
camera: ^0.7.0+2
flutter_file_dialog: ^1.0.0

何卒よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

createStateで新たにStateウィジェットを作り、その中に_saveFileの関数を入れ、onPressed:_saveFileとすることで、無事関数が作動しました。考えてくださった皆様、ありがとうございました。

投稿2021/03/24 13:31

sugoroku

総合スコア5

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問