yonBav
yonBav

Reputation: 1915

Flutter object is not initialized after initState

I'm new to flutter, and i bumped into a problem.

I have a Feed model in my app that looks like this:

import 'package:uuid/uuid.dart';

class Feed {

  // Static Members
  var uuid = new Uuid();

  // Members
  String   id;
  bool     isScheduled;
  DateTime createdTime;
  DateTime feedingTime;
  String   deviceId;

  // Constructors
  Feed({this.feedingTime, this.deviceId, this.isScheduled}) {
    id = uuid.v4();
    createdTime = DateTime.now();
  }

  Feed.fromDevice(deviceId) {
    Feed(deviceId: deviceId, feedingTime: DateTime.now(), isScheduled: false);
  }
}

Now i have my AddFeedForm that i'm trying to initialize with default values, in the InitState:

class _AddFeedFormState extends State<AddFeedForm> {
  // Final Members
  final _formKey = GlobalKey<FormState>();
  final List<Machine> _devices = machinesFromServer;

  // Members
  Feed _feed;

  @override
  void initState() {
    _feed = Feed.fromDevice(_devices.first.id);
    super.initState();
  }

But somehow after the initState the _feed parameter stays null!

Any ideas?

Upvotes: 1

Views: 4551

Answers (1)

Danny Tuppeny
Danny Tuppeny

Reputation: 42373

But somehow after the initState the _feed parameter stays null!

Are you sure this is the case, and not that you're getting a Feed instance that has null fields?

It looks like your named constructor is incorrect:

Feed.fromDevice(deviceId) {
  Feed(deviceId: deviceId, feedingTime: DateTime.now(), isScheduled: false);
}

Here you're calling the default Feed constructor inside a named constructor, but not doing anything with the result - this is creating another Feed and then throwing it away. The one returned by the named constructor has not been initialised.

What you probably wanted was this:

Feed.fromDevice(deviceId):
  this(deviceId: deviceId, feedingTime: DateTime.now(), isScheduled: false);

This makes the fromDevice constructor call the default constructor for initialisation of the instance, rather than creating another copy that goes unused.

Another option would be to make it a static method:

static fromDevice(deviceId) {
  return Feed(deviceId: deviceId, feedingTime: DateTime.now(), isScheduled: false);
}

There wouldn't be much difference in this case.. Constructors seem nicer, but sometimes you might find that you want to a) make initialisation async (static methods can return a Future<Feed> but constructors cannot or b) do more processing of the arguments before they're passed to the real constructor that might not fit nicely in the initialiser call.

Upvotes: 3

Related Questions