gpt4 book ai didi

dart - Flutter 有状态类

转载 作者:IT王子 更新时间:2023-10-29 06:55:17 26 4
gpt4 key购买 nike

Flutter 新手,通常是编程新手。

目标:我正在尝试创建一个可以从我的 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)
],
)
)
);
}
}

上面的目标是通过传入在 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) 时,主要出现红线错误,如下所示:“无法将元素类型 StatefulForm 分配给列表类型小部件”。

有人对此有什么建议吗?甚至可以创建可以重复调用的有状态 Assets 吗?

最佳答案

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

至少,尝试通过这个 flutter get started页面和this tutorial .

不过用我自己的话来说是一个 TLDR。我对基本的 Flutter 模板做了一些修改,以使用无状态小部件来说明这一点。

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 有两种主要类型的小部件供您编写 - 有状态小部件和无状态小部件。

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

Stateful widgets 比 StatelessWidgets 稍微复杂一些,实际上分为两部分。您需要为每个编写一个类。

第一个类扩展了 StatefulWidget,负责保存从构造函数传入的内容,仅此而已(稍后您可以开始使用它来处理更多内容,但我们不要混淆它)。在示例中,保存的数据是 title。这在某种程度上与 StatelessWidget 所做的相同,但没有构建功能。

扩展 State 的类实际上负责构建。但它也可以做更多的事情。它有一个你可以调用的 .setState(() { ....}) 方法,这将使小部件稍后重新构建(即调用构建函数),但无论有什么新的您保存的数据。您可以像本例中那样作为按下按钮的结果调用它,或者作为对网络等的异步调用的结果调用它,但不要直接从构建函数调用它(它可以在构建中的回调中功能)。

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

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

希望对您有所帮助!但老实说,看完 flutter 网站上的所有教程,你会学到比我更多的东西!

关于dart - Flutter 有状态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50159177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com