你的问题存在,因为你传递给
我创建了一个类,用于存储带有参数的名为CardWidget的小部件。我把它存储在不同的文件中,以便多次使用。CardWidget是一个Widget,包含文本数据,如标题,描述,日期和帐户。我需要它在主页上创建特殊的板,就像它曾经在不同的论坛。
。小部件文件
import 'package:flutter/material.dart';
class CardWidget extends StatelessWidget {
const CardWidget({Key? key, pcolor, ptext, paccount, pdate, peoplein}) : super(key: key);
Widget CardWid({pcolor, ptext, paccount, pdate, peoplein}) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
// data was erased for economy
child: Container());
}
@override
Widget build(BuildContext context) {
return CardWid();
}
}
当我从另一个flutter类调用它时,它返回一个问题。
类型'Null'不是类型'String'的子类型
。主文件,我在其中调用小部件并给出参数
class HomePageState extends State<HomePage> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
CardWidget(
pcolor: Colors.orangeAccent,
ptext: 'I need team for First Person Shooter',
paccount: 'gamedev21',
pdate: 'February 12, 2023, 21:00',
peoplein: 2),
CardWidget(
pcolor: Colors.green[700],
ptext: 'text',
paccount: 'text',
pdate: 'February 12, 2023, 18:00',
peoplein: 4),
],
),
);
}
您应该在构造函数中键入参数,并在Widget本身中定义它们,如下所示
你的问题存在,因为你传递给CardWidgets
的构造函数的值实际上并没有被保存在任何地方,所以当CardWid
方法被调用时,参数(类型dynamic
)是空的。
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Scaffold(body:CardWidget(
pcolor: Colors.orangeAccent,
ptext: 'I need team for First Person Shooter',
paccount: 'gamedev21',
pdate: 'February 12, 2023, 21:00',
peoplein: 2,
),);
}
}
class CardWidget extends StatelessWidget {
const CardWidget({
Key? key,
required this.pcolor,
required this.ptext,
required this.paccount,
required this.pdate,
required this.peoplein,
}) : super(key: key);
final Color pcolor;
final String ptext;
final String paccount;
final String pdate;
final int peoplein;
Widget cardWidget() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
color: pcolor,
child: Column(
children: [
Text("$ptext, $paccount, $pdate, $peoplein"),
],
),
);
}
@override
Widget build(BuildContext context) {
return cardWidget();
}
}
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}