PJQuakJag
PJQuakJag

Reputation: 1247

Flutter Stateful Classes

New to flutter and generally new to programming.

Goal: I'm trying to create a stateful text field that I can call from my main (passing a name of the field and a limit for the field). Basically, I'm trying to be concise and reduce the amount of code for consecutive text fields.

I have the following code in the main:

import 'package:flutter/material.dart';
import 'package:ui_practice2/StatefulForm.dart';

void main() => runApp(new KangarooApp());

class KangarooApp extends StatelessWidget {
  Widget build(BuildContext context){
    return new MaterialApp(
      home: MyStateful(),
    );
  }
}
class MyStateful extends StatefulWidget {
  MyStateful({Key key, this.title}): super(key: key);
  final String title;
  @override
  MyState createState() => new MyState();
}
class MyState extends State<MyStateful> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
        title: new Text("Assets")
    ),
      body: new Container(
          margin: new EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
          child: new ListView(
            children: <Widget>[
              new StatefulForm("Peter", 10)
            ],
      )
      )
    );
  }
}

The goal of the above is to call the StatefulForm class by passing in two arguments that is found in StatefulForm.dart, below:

import 'package:flutter/material.dart';
import 'package:ui_practice2/main.dart';


class StatefulForm extends State<MyStateful> {
  final TextEditingController _texteditcontrol = new TextEditingController();
  String fieldName = "";
  int maxLength = 0;

  @override
  StatefulForm(String text, int limitNum){
    fieldName= text;
    maxLength = limitNum;
  }
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return new Theme(
        data: theme.copyWith(primaryColor: Color.fromRGBO(33, 206, 153, 1.0)),
        child: new TextField(
          maxLength: maxLength,
          controller: _texteditcontrol,
          decoration: new InputDecoration(
              labelText: fieldName),
          onChanged: (String e) {
            setState (() {
              fieldName = e;
            });
          },
        )
    );
  }
}

I get the red line error in the main when I call StatefulForm("Peter",10) that is the following: "The element type StatefulForm cannot be assigned to the list type widget".

Anyone have any advice on this? Is it even possible to create an stateful asset that can be repeatedly called?

Upvotes: 2

Views: 3352

Answers (1)

rmtmckenzie
rmtmckenzie

Reputation: 40433

I don't want to write a read the docs kind of answer here, but I honestly think that reading the documentation would be a good idea as it will probably do a much better job of explaining than I will.

At the very least, try following through this the flutter get started page and this tutorial.

A TLDR in my own words though. I've modified the basic flutter template a very little bit to illustrate this with a stateless widget.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(widget.title),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug paint" (press "p" in the console where you ran
          // "flutter run", or select "Toggle Debug Paint" from the Flutter tool
          // window in IntelliJ) to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new TimesPressedDisplay(numTimesPressed: _counter);
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class TimesPressedDisplay extends StatelessWidget {
  final int numTimesPressed;

  TimesPressedDisplay({@required this.numTimesPressed}):
    assert(numTimesPressed != null);

  @override
  Widget build(BuildContext context) {
    return new Text(
      '$numTimesPressed',
      style: Theme.of(context).textTheme.display1,
    ),
  } 
}

Flutter has two main types of widgets that you will write - Stateful Widgets and Stateless Widgets.

Let's start with Stateless Widgets. They can have a constructor and methods, but can only have final members as they aren't supposed to change after they're built. They have a build function that you build a bunch of widgets inside, using the members. In the sample, see TimesPressedDisplay and NumTimesPressed. You could definitely do this without the StatelessWidget (i.e. copy and paste it's build function into wherever it is being built), but by using a statelessWidget you've created something you can re-use somewhere else (and reduced the amount of code in one function).

Stateful widgets are slightly more complicated than StatelessWidgets, and are actually split into two parts. You need to write a class for each.

The first class extends StatefulWidget, and is responsible for holding things passed in from the constructor, and not much more (waaay later on you can start using it for more things but let's not confuse this). In the example, the data is saves is the title. This is sort of the same as what StatelessWidget does, but without the build function.

The class that extends State actually does the building. But it has a little bit more it can do as well. It has a .setState(() { ....}) method you can call, which will make the widget re-build (i.e. the build function will be called) later, but with whatever new data you save. You can call that as a result of a button being pressed as in this example, or the result of an asynchronous call to the network etc, but don't call it directly from the build function (it can be in a callback within the build function though).

The idea is that the widget extending state will have mutable member variables (_counter in the example). These represent the current state of the widget. The convention is that members used in the build function are only modified within a setState callback.

There is one more thing to get used to - in some languages/frameworks, you'd want to try to use as few instances of widgets as possible, and to re-use them. Flutter is instead optimized to make instances again and again with different parameters, and build them in an optimized way. So instead of saving a value in a Stateful Widget and modifying it (as it looks like you are trying to do), it's actually more more optimal to pass in the value to the constructor of a Stateless widget, save it in a member, and then use in the build function.

Hope that helps! But honestly, following through all the tutorials on the flutter website will teach you more than I can!

Upvotes: 4

Related Questions