简体   繁体   中英

dart stateful widget pass data to state error: widget is null

I want to download images from firebase storage and cache them. But I'm facing a problem when i would pass the path from the Stateful widget to the state.

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);
  }
}

The problem is the line:

String path = widget.mPath;

It throws an error:

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)
[....]

Any ideas?

You can't access to the widget on your State constructor because the element is not associated yet, move that to your initState method inside your state:

          @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;
                })
            );
          }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM