四、使用 final 修饰 Widget 组件成员变量分析
组件属性必须使用 final 修饰 , 如果不使用 final 修饰组件属性 , 会有如下报错 ;
Can't define a const constructor for a class with non-final fields. (Documentation) Try making all of the fields final, or removing the keyword 'const' from the constructor.
我们自定义的 StudentWidget 继承了 StatelessWidget 类 , StatelessWidget 继承了 Widget ;
abstract class StatelessWidget extends Widget { }
Widget 类由 @immutable 注解修饰 , 被该注解修饰的类 , 该类以及其子类中 的 成员变量都是不可变的 , 即都要被 final 类型修饰 ;
@immutable abstract class Widget extends DiagnosticableTree { }
五、调用自定义组件
1、主要方法
在 main.dart 中 , 使用如下代码 , 创建组件 ;
StudentStatelessWidget( name: "Tom", age: 18 ), StudentStatefulWidget( name: "Jerry", age: 16 ),
2、完整代码
完整代码 :
import 'package:flutter/material.dart'; import 'package:flutter_widget/widget/student_stateful_widget.dart'; import 'package:flutter_widget/widget/student_stateless_widget.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ StudentStatelessWidget( name: "Tom", age: 18 ), StudentStatefulWidget( name: "Jerry", age: 16 ), Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
3、效果展示
效果展示 : 红色矩形框中是显示的两个组件 ;