我想制作一个额外的文件“extra.dart”,我想在其中添加我的顶级容器和四个 TextButtonWidget。1 个 ColorWidget,4 个 TextButtonWidget,每个都有 colorwidget 作为他们的孩子。
我将顶部容器小部件命名为 ColorWidget,并将文本按钮小部件中的该小部件作为其子级重用。
!!我需要在 ColorWidget() 中将颜色设置为必需的命名参数,但对我来说总是出错。
所以在 extra.dart 中应该是所有小部件,而在 main.dart 中只是我从 extra.dart 调用所有小部件的基本布局。
不用担心 switchlisttiles。如果您想添加它们,它们意味着创建边框,并使容器尺寸更大,所有这些都应用于顶部容器。
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'extra.dart';
// ONLY USE STATEFUL WIDGETS IF CONTENT ON SCREEN HAS TO CHANGE DYNAMICALLY!!
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final String title = 'Test';
final String name = 'John Doe';
@override
//
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Home(),
),
);
}
}
// var colorChange = true;
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Color color = Colors.amber;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Container color")),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Container(
decoration: BoxDecoration(
color: color,
borderRadius: const BorderRadius.all(Radius.circular(10))),
height: 100,
width: 100,
),
),
const SizedBox(
height: 20,
),
Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: TextButton(
onPressed: () {
setState(() {
color = Colors.amber;
});
},
child: Container(
decoration: const BoxDecoration(
color: Colors.amber,
borderRadius:
BorderRadius.all(Radius.circular(10))),
height: 100,
width: 100,
),
),
),
Center(
child: TextButton(
onPressed: () {
setState(() {
color = Colors.blue;
});
},
child: Container(
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius:
BorderRadius.all(Radius.circular(10))),
height: 100,
width: 100,
),
),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: TextButton(
onPressed: () {
setState(() {
color = Colors.red;
});
},
child: Container(
decoration: const BoxDecoration(
color: Colors.red,
borderRadius:
BorderRadius.all(Radius.circular(10))),
height: 100,
width: 100,
),
),
),
Center(
child: TextButton(
onPressed: () {
setState(() {
color = Colors.green;
});
},
child: Container(
decoration: const BoxDecoration(
color: Colors.green,
borderRadius:
BorderRadius.all(Radius.circular(10))),
height: 100,
width: 100,
),
),
)
],
),
)
],
)
],
),
);
}
}