颤动的有状态类

时间:2018-05-03 15:49:51

标签: dart flutter

新的扑动,通常是编程的新手。

目标:我正在尝试创建一个有状态的文本字段,我可以从我的主要调用(传递字段的名称和字段的限制)。基本上,我正在努力简洁并减少连续文本字段的代码量。

我在主要代码中有以下代码:

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

上面的目标是通过传入StatefulForm.dart中的两个参数调用StatefulForm类,如下所示:

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

当我调用StatefulForm(“Peter”,10)时,我在main中得到红线错误:“元素类型StatefulForm无法分配给列表类型小部件”。

有人对此有任何建议吗?甚至可以创建一个可以重复调用的有状态资产吗?

1 个答案:

答案 0 :(得分:2)

我不想在这里写一篇阅读文档的答案,但老实说我认为阅读文档会是一个好主意,因为它可能会做得更好解释比我愿意。

至少,请尝试完成此问题get started页面和this tutorial

用我自己的话说TLDR。我已经修改了基本的颤振模板,用一个无状态的小部件来说明这一点。

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有两种主要类型的小部件,您将编写它们 - Stateful Widgets和Stateless Widgets。

让我们从Stateless Widgets开始。他们可以有一个构造函数和方法,但只能有final个成员,因为他们在构建之后不应该更改。它们具有build函数,您可以使用成员在其中构建一组小部件。在示例中,请参阅TimesPressedDisplay和NumTimesPressed。你绝对可以在没有StatelessWidget的情况下做到这一点(即将它的构建功能复制并粘贴到它所在的任何地方),但是通过使用statelessWidget你已经创建了一些你可以在其他地方重用的东西(并减少了)一个函数中的代码量。)

状态小部件比StatelessWidgets稍微复杂一些,实际上分为两部分。您需要为每个人编写课程。

第一个类扩展了StatefulWidget,并且负责保存从构造函数传入的内容,而不是更多(稍后你可以开始使用它来获取更多东西但是不要混淆这个)。在示例中,数据保存为title。这与StatelessWidget的功能相同,但没有构建功能。

扩展State的类实际上构建了该类。但它还可以做多一点。它有一个.setState(() { ....})方法,你可以调用它,这将使窗口小部件重新构建(即稍后将调用构建函数),但是你可以保存任何新数据。您可以在此示例中按下按钮,或者对网络进行异步调用等结果调用它,但不要直接从构建函数调用它(它可以在内部回调中调用它)虽然构建功能。)

我们的想法是扩展state的小部件将具有可变成员变量(示例中为_counter)。这些代表小部件的当前状态。惯例是构建函数中使用的成员仅在setState回调中被修改。

还有一件事需要习惯 - 在某些语言/框架中,您希望尝试使用尽可能少的widgets实例,并重新使用它们。相反,Flutter经过优化,可以使用不同的参数反复创建实例,并以优化的方式构建它们。因此,不是在有状态窗口小部件中保存值并修改它(因为它看起来像你正在尝试做的那样),实际上将值传递给无状态窗口小部件的构造函数实际上更加优化,将其保存在一个成员,然后在构建函数中使用。

希望有所帮助!但老实说,通过flutter网站上的所有教程,我会教你更多的东西!