通过类的构造函数来传递参数
代码示例:
import 'package:flutter/material.dart';
import 'test.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('flutter')),
body: Center(child: Home())));
}
}
class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Container(
child: Column(
children: [
//构造函数传递参数
Home2(msg: 'hh')
],
),
),
decoration: BoxDecoration(
color: Colors.red,
border: Border.all(color: Colors.yellow, width: 20.0)),
height: 200,
width: 200,
alignment: Alignment.center,
);
}
}
//无状态组件传递参数
class Home2 extends StatelessWidget {
final String msg;
const Home2({Key key, this.msg}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Text('${this.msg}'),
);
}
}
//有状态组件传递参数
class Home2 extends StatefulWidget {
Home2({Key key, this.msg}) : super(key: key);
final String msg;
@override
_Home2State createState() => _Home2State(this.msg);
}
class _Home2State extends State<Home2> {
String msg2;
_Home2State(this.msg2);
@override
Widget build(BuildContext context) {
return Container(child: Text('${msg2}')
// Text('${widget.msg}'),方式一,widget代表根组件
//Text('${msg2}',方式二,有无this都可以
);
}
}