我成功地通过以下方式将Stateful类变量的值传递给State类的构造函数:
我通过构造函数将Stateful类变量的值传递给了State类:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
home: MyHomePage('John', 'Morison'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage(this.fname, this.lname);
final String fname;
final String lname;
@override
_MyHomePageState createState() => _MyHomePageState(fname, lname);
}
class _MyHomePageState extends State<MyHomePage> {
_MyHomePageState(this.fname, this.lname);
final String fname;
final String lname;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Hello $fname $lname'),
)
);
}
}
这很奇怪,因为有超过两个变量,我必须做很多工作。是否有更好的方法?