我想从Firebase存储下载图像并缓存它们。 但是当我将路径从有状态小部件传递到状态时,我遇到了一个问题。
class FirebaseCachedImage extends StatefulWidget{
final String mPath;
FirebaseCachedImage({ Key key, this.mPath }) : super(key: key);
@override
State<StatefulWidget> createState() => _FirebaseCachedImage();
}
class _FirebaseCachedImage extends State<FirebaseCachedImage> {
final FirebaseStorage storage = FirebaseStorage(app: Firestore.instance.app, storageBucket: 'gs://fluttertest-b7c52.appspot.com/');
Uint8List imageBytes;
String errorMsg;
_FirebaseCachedImage() {
String path = widget.mPath;
storage.ref().child(path).getData(10000000).then((data) =>
setState(() {
imageBytes = data;
})
).catchError((e) =>
setState(() {
errorMsg = e.error;
})
);
}
@override
Widget build(BuildContext context) {
var img = imageBytes != null ? Image.memory(imageBytes, fit: BoxFit.cover,) : Text(errorMsg != null ? errorMsg : "Loading...");
return new Container(child: img);
}
}
问题出在那行:
String path = widget.mPath;
它抛出一个错误:
The following NoSuchMethodError was thrown building MyGridTile:
I/flutter (11523): The getter 'mPath' was called on null.
I/flutter (11523): Receiver: null
I/flutter (11523): Tried calling: mPath
I/flutter (11523):
I/flutter (11523): When the exception was thrown, this was the stack:
I/flutter (11523): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter (11523): #1 new _FirebaseCachedImage (package:pre_alpha_release/firebase_cached_image.dart:21:26)
I/flutter (11523): #2 FirebaseCachedImage.createState (package:pre_alpha_release/firebase_cached_image.dart:12:42)
I/flutter (11523): #3 new StatefulElement (package:flutter/src/widgets/framework.dart:3746:23)
I/flutter (11523)
[....]
有什么想法吗?
答案 0 :(得分:0)
您无法访问State
构造函数上的小部件,因为该元素尚未关联,请将其移至状态内的initState
方法中:
@override
void initState() {
super.initState();
String path = widget.mPath;
storage.ref().child(path).getData(10000000).then((data) =>
setState(() {
imageBytes = data;
})
).catchError((e) =>
setState(() {
errorMsg = e.error;
})
);
}