Young
Young

Reputation: 1091

How to use a builder function on a StatefulWidget

I am trying to create a flutter app. I am trying to use a builder function for a hero tag like this:

import 'package:flutter/material.dart';

void main() => runApp(Page());

class Page extends StatefulWidget {

  final String open;

  Page({this.open});

  @override
  PageState createState() => PageState();

}

class PageState extends State<Page> {

  String open;

  @override
  Widget build(BuildContext context) {

    return MaterialApp (
      home: Scaffold (
        body: Hero (
          tag: open,
          child: Material ()
        )
      )
    );
  }

}

But this code gives me an error Saying

Failed assertion: line 128 pos 15: 'tag != null': is not true

How should I change my code?

Upvotes: 1

Views: 65

Answers (1)

anmol.majhail
anmol.majhail

Reputation: 51206

You need to pass string as Page() is expecting one, so it can assign it to hero tag.

Plus in state you can access that string with widget. method.

import 'package:flutter/material.dart';

void main() => runApp(Page(
      open: 'open',  // Add this
    ));

class Page extends StatefulWidget {
  final String open;

  Page({this.open});

  @override
  PageState createState() => PageState();
}

class PageState extends State<Page> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(body: Hero(tag: widget.open, child: Material())));
  }
}

Upvotes: 1

Related Questions