gpt4 book ai didi

flutter - Flutter错误: The element type 'Button' can't be assigned to the list type 'Widget'

转载 作者:行者123 更新时间:2023-12-03 04:21:33 26 4
gpt4 key购买 nike

我不知道为什么我会出现此错误。我在这里编写了button.dart文件:

 import 'package:flutter/material.dart';

class Button {
double left;
double top;
String text;
Button(this.text,this.top,
this.left);

Widget button(){
return Positioned(
left:left,

top: top,
child:Container(
height: 54,
width: 157,

color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(49))
),
child: Center(
child: Text(text,
style: TextStyle(
fontFamily: 'MontserratAlternates',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
fontSize: 20,
letterSpacing: -0.02,
color:Colors.black,

),
),
)
),),
);

}
}

然后我将其编码在main.dart文件中,但是它不起作用,然后出现错误“元素类型Button不能分配给列表类型'Widget'”,我不明白为什么我会发生此错误。
这是main.dart:
import 'package:flutter/material.dart';
import './number.dart';
import'./image.dart';
import './button.dart';
void main() {
runApp(Main());
}

class Main extends StatelessWidget {

@override
Widget build(BuildContext context){



return MaterialApp(
title: 'Main',
home: Scaffold(
body: Container(

child: Stack(
children:<Widget> [

image(context),
Number(),
Button("Start",412,45),


],
),
),
),
);
}
}

系统警告我,所以我不应该像大多数代码那样编写。

最佳答案

您的自定义窗口小部件应继承自StatefulWidget或StatelessWidget。通过扩展其中任何一个,Flutter会将您的类(class)识别为小部件。

class Button extends StatelessWidget {
final double left;
final double top;
final String text;

Button(this.text, this.top, this.left);

@override
Widget build(BuildContext context) {
return Positioned(
left: left,
top: top,
child: Container(
height: 54,
width: 157,
color: Colors.transparent,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(49))),
child: Center(
child: Text(
text,
style: TextStyle(
fontFamily: 'MontserratAlternates',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
fontSize: 20,
letterSpacing: -0.02,
color: Colors.black,
),
),
),
),
),
);
}
}

否则,如果要使用 button函数执行此操作,则需要在创建 Button之后调用该函数。
import 'package:flutter/material.dart';
import './number.dart';
import './image.dart';
import './button.dart';

void main() {
runApp(Main());
}

class Main extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Main',
home: Scaffold(
body: Container(
child: Stack(
children: <Widget>[
image(context),
Number(),
Button("Start", 412, 45).button(),
],
),
),
),
);
}
}

关于flutter - Flutter错误: The element type 'Button' can't be assigned to the list type 'Widget' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62292390/

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