简体   繁体   中英

Flutter StatefulWidget has no widget property

I have a StatefulWidget that sets a backend for Android:

class ToeKickSettings extends StatefulWidget {
  ToeKickSettings({
    Key key,
    this.backend
  }) : super(key: key);
  final AndroidBackend backend;
  @override
  _ToeKickSettingsState createState() => _ToeKickSettingsState();
}

class _ToeKickSettingsState extends State<ToeKickSettings> {
  double default_bottom_spacing = 5;
  List<Widget> listChildren = [];

  _ToeKickSettingsState() {
    generateListsFromSoundPacks().then((val) => setState(() {
      listChildren = val;
    }));
  }

  Future<List<Widget>> generateListsFromSoundPacks() async {
    List<Widget> list = new List<Widget>();
    List<String> soundPacks = await widget.backend.common.listSoundPacks();
    //...
  }
 }

I access the backend on the state part of the StatefulWidget by doing await widget.backend.common.listSoundPacks();

I'm getting this error:

E/flutter (23645): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The getter 'backend' was called on null.
E/flutter (23645): Receiver: null
E/flutter (23645): Tried calling: backend
E/flutter (23645): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (23645): #1      _ToeKickSettingsState.generateListsFromSoundPacks (package:flutter_app/toe_kick.dart:131:44)

Which suggests that there's no widget property when generateListsFromSoundPacks is called. I suspect it has to do with how early I call _ToeKickSettingsState() , from _ToeKickSettingsState createState() => _ToeKickSettingsState(); . It's possible that the wodget property hasn't been setted yet.

What can I do?

Do not use widget in the State class 's constructor, move the code in constructor to initState .

  @override
  void initState() {
    super.initState();
    generateListsFromSoundPacks().then((val) => setState(() {
      listChildren = val;
    }));
  }

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