gpt4 book ai didi

image - Flutter Navigation 和同时对 dispose() 的要求

转载 作者:IT王子 更新时间:2023-10-29 07:12:32 24 4
gpt4 key购买 nike

尝试使用 image_picker在 Flutter 中,我遇到以下问题:

当导航应该返回到 Widget Nr1 时,我无法再在 Widget Nr1 中调用 setState()。这是因为当 Navigation.push 从 Widget-Nr1 到 Widget-Nr2 时调用了 dispose() 方法。

事实证明,我绝对需要调用此 dispose() 方法才能使 image_picker 插件正常工作。 (如果我不这样做,那么错误 ...was disposed with an active Ticker... 发生,可能是由于 image_picker 插件在迫切需要预先处理()的引擎盖。

反正我是蛇咬尾部的感觉。

作为总结,我执行以下操作(另请参见下面的代码):

  • 在 Widget Nr1 内部:按下 FloatingAction-Button,将导航器推送到 Widget Nr2
  • 两个小部件(Nr1 和 Nr2)都是有状态的小部件
  • 它们都有一个 dispose-method(需要否则 image_picker 不起作用)
  • Widget-Nr2 调用 image_picker 插件(让用户用相机拍照并要求用户提供一些描述图像的字符串文本)
  • 结果(即图像文件和一些字符串文本)需要返回给 Widget-Nr1(使用 Navigation.pop)
  • Widget-Nr1 实际上确实获取了这些数据(即图像加上一些字符串文本)
  • 但是:在 Navigation.pop 之后它不能再调用 setState() 很可能是因为两个 Widget 都已经调用了它们的 dispose() 方法<

我在 Widget-Nr1 中得到错误:

Dart Error: Unhandled exception:
setState() called after dispose()

我该怎么做才能完成这项工作?

如何在 Widget-1 中再次使用 image_picker 的结果数据(在 Widget-1 中需要 dispose())作为 Navigation.pop 结果这在所有导航之后 setState() 仍然可行的方式 ??

或者还有其他方法可以使用吗?

这是我的代码:

StatefulWidget Nr1(摘录):

    child: FloatingActionButton(
onPressed: () async {
_imagePickerResult = await navigateToImagePicker(context);
setState(() async {
this.itemBins.add(ItemBin(
_imagePickerResult.locationName,
_imagePickerResult.locationImage));
});
},
child: Icon(Icons.add),
),

// ...

Future<ImagePickerResult> navigateToImagePicker(BuildContext context) async {
return await Navigator.push(
context, MaterialPageRoute(builder: (context) => MyImagePickerView())
);
}

// ...

class ImagePickerResult {
String locationName;
Image locationImage;

ImagePickerResult({this.locationName, this.locationImage});
}

StatefulWidget Nr2:

    import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import './../../models/image_picker_location.dart';

class MyImagePickerView extends StatefulWidget {
_MyImagePickerViewState createState() => _MyImagePickerViewState();
}

class _MyImagePickerViewState extends State<MyImagePickerView> {
TextEditingController _myController = TextEditingController();
File _imageFile;
bool _pickImage = true;

@override
Widget build(BuildContext context) {
if (_pickImage) {
return FutureBuilder<File>(
future: ImagePicker.pickImage(source: ImageSource.camera),
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.hasData) {
_pickImage = false;
_imageFile = snapshot.data;
return _showImage(snapshot.data);
} else {
return Scaffold(
body: Center(
child: Text('no image picker availalbe'),
),
);
}
},
);
} else {
return _showImage(_imageFile);
}
}

Widget _showImage(File imgFile) {
return Scaffold(
body: Stack(
alignment: AlignmentDirectional.topStart,
children: <Widget>[
Positioned(
left: 0.0,
bottom: 0.0,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Center(
child: imgFile == null
? Text('No image selected.')
: Image.file(imgFile),
),
),
Positioned(
left: 16.0,
bottom: 70.0,
width: MediaQuery.of(context).size.width - 32.0,
height: 50.0,
child: Container(
color: Colors.grey[100],
child: TextField(
autofocus: false,
keyboardType: TextInputType.text,
autocorrect: false,
style: TextStyle(
color: Colors.black,
fontSize: 22.0,
fontWeight: FontWeight.w600),
decoration: InputDecoration(
hintStyle: TextStyle(
color: Colors.black38,
fontSize: 22.0,
fontWeight: FontWeight.normal),
hintText: "depart From :",
contentPadding: const EdgeInsets.fromLTRB(6.0, 13.0, 0, 12.0),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 2.0),
),
),
maxLines: 1,
textAlign: TextAlign.left,
controller: _myController,
onEditingComplete: () {
FocusScope.of(context)
.requestFocus(FocusNode()); // dismiss keyboard
Navigator.pop(
context,
ImagePickerResult(
locationName: _myController.text,
locationImage: Image.file(imgFile),
),
);
},
),
),
),
],
),
);
}
}

Widget Nr1 的处理方法:

  @override
void dispose() {
if (_debounce?.isActive ?? false) {
_debounce.cancel(); // if _debounce is active cancel it...
}
_debounce = Timer(const Duration(milliseconds: 200), () {
// security wait due to the fact that there are animations still running during setState()
});
// dispose AnimationController
controller.dispose();
_debounce.cancel();
super.dispose();
}

Widget-Nr2的dispose方法:

   @override
void dispose() {
_myController.dispose();
super.dispose();
}

如果我不让 view1 在 image_picker 启动之前执行 dispose(),则会出现错误消息... ) 在 image_picker 的 segue 发生之前人工“等待”200 毫秒)...

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown while finalizing the widget tree:
flutter: _HistoryViewState#a8eac(ticker active but muted) was disposed with an active Ticker.
flutter: _HistoryViewState created a Ticker via its SingleTickerProviderStateMixin, but at the time dispose()
flutter: was called on the mixin, that Ticker was still active. The Ticker must be disposed before calling
flutter: super.dispose(). Tickers used by AnimationControllers should be disposed by calling dispose() on the
flutter: AnimationController itself. Otherwise, the ticker will leak.
flutter: The offending ticker was: Ticker(created by _HistoryViewState#a8eac(lifecycle state: created))
flutter: The stack trace when the Ticker was actually created was:
flutter: #0 new Ticker.<anonymous closure>
package:flutter/…/scheduler/ticker.dart:64
flutter: #1 new Ticker
package:flutter/…/scheduler/ticker.dart:66
flutter: #2 __HistoryViewState&State&SingleTickerProviderStateMixin.createTicker
package:flutter/…/widgets/ticker_provider.dart:93
flutter: #3 new AnimationController

最佳答案

代替 setState(() {...}),尝试 if (mounted) { setState(() {...}) } 代码可能在用户导航离开后运行。

关于image - Flutter Navigation 和同时对 dispose() 的要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54599561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com