有人能告诉我为什么会这样吗?
当我尝试添加一个实现appBar flutter的类AppBarDesign时,会出现以下错误。
错误:参数类型'AppBarDesign'无法分配给参数类型'PreferredSizeWidget'。(argument_type_not_assignable[flutterbyrajath]lib\main. dart:27)
import 'package:flutter/material.dart';
main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Rajath\'s design ',
debugShowCheckedModeBanner: false,
theme: new ThemeData(primarySwatch: Colors.amber),
home: new MyHomePage(key, 'App is Fun'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage(Key key, this.title) : super(key: key);
final title;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBarDesign(key, title),
);
}
}
class AppBarDesign extends StatelessWidget {
AppBarDesign(Key key, this.title) : super(key: key);
final title;
@override
Widget build(BuildContext context) {
return new AppBar(
title: new Text(title),
);
}
}
无需搜索任何其他主题即可实现的有用提示:
class ApplicationToolbar extends StatelessWidget with PreferredSizeWidget{
@override
Widget build(BuildContext context) {
return AppBar( ... );
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
脚手架需要一个实现PreferredSizeWidget的类作为appbar
将您的自定义appbar包装成PreferredSize
Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(100),
child: Container(color: Colors.red),
),
)
或实现PreferredSizeWidget:
Scaffold(
appBar: MyAppBar(),
)
...
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Size get preferredSize => const Size.fromHeight(100);
@override
Widget build(BuildContext context) {
return Container(color: Colors.red);
}
}
截图:
创建这个类:
class CustomAppBar extends PreferredSize {
@override
final Widget child;
final double height;
CustomAppBar({
required this.height,
required this.child,
}) : super(child: child, preferredSize: Size.fromHeight(height));
}
用法:
appBar: CustomAppBar(
height: 100,
child: Container(
color: Colors.red,
child: Column(
children: [
Text('0'),
Text('1'),
Text('2'),
Text('3'),
],
),
),
)